尝试使用触摸事件在另一个图像上绘制图像

在我的应用程序中,我有一个名为mainvie的视图 – 当应用程序运行时,mainview被加载,将背景图像加载到屏幕上(下面的代码)ring_large.jpg已被添加为文件。

- (void)drawRect:(CGRect)rect { UIImage *image = [UIImage imageNamed:@"rink_large.jpg"]; CGPoint imagepoint = CGPointMake(10,0); [image drawAtPoint:imagepoint]; } 

这工作正常,这是当我试图绘制另一个形象,这是我有问题。 其他地方(文件名为mainviewcontroller.m) – 即使我正在尝试获取触摸的位置,然后在该位置绘制图像。 下面列出的是我的代码。 我不知道为什么我想要放置的图像根本不是绘图。 我确定它不是在溜冰场图像后面绘制的,因为我评论了这一点,点击时图像仍然没有绘制。 这里是应该绘制图像的触摸开始function。

 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { CGPoint location = [[touches anyObject] locationInView:mainView]; UIImage *image = [UIImage imageNamed:@"small_cone.png"]; [image drawAtPoint:location]; } 

任何人都可以看到为什么图像不会画什么时候触摸的地方? 触摸开始function在任何地方触摸屏幕时开始,但图片不显示。 感谢您的帮助,我更新的客观 – C。

UIImage drawAtPoint在当前graphics上下文中绘制图像。 您没有定义graphics上下文。 在drawRect(你的原始代码是)已经有一个graphics上下文。 基本上,你是告诉UIImage要画什么位置,而不是画什么。

你需要更多这样的东西:

 CGPoint location = [[touches anyObject] locationInView:mainView]; UIGraphicsBeginImageContext(mainView.bounds.size); UIImage *image = [UIImage imageNamed:@"small_cone.png"]; [image drawAtPoint:location]; UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); 

但是,这不会保留或考虑您的原始图像。 如果你想让它们两个都被绘制,那么使用两个图像的drawAtPoint:

 CGPoint location = [[touches anyObject] locationInView:mainView]; UIGraphicsBeginImageContext(mainView.bounds.size); UIImage *image = [UIImage imageNamed:@"rink_large.jpg"]; CGPoint imagepoint = CGPointMake(10,0); [image drawAtPoint:imagepoint]; image = [UIImage imageNamed:@"small_cone.png"]; [image drawAtPoint:location]; UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); 

现在你可以用newImage做一些事情,它包含两个图像的组合。