【问题标题】:Attempting to draw image on top of another image using a touch event尝试使用触摸事件在另一个图像上绘制图像
【发布时间】:2012-10-25 11:07:20
【问题描述】:

在我的应用程序中,我有一个名为 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 的文件) - 在触摸时,即使我试图获取触摸的位置,并在该位置绘制图像。下面列出的是我的代码。我不确定为什么我要放置的图像根本没有绘制。我确定它没有在溜冰场图像后面绘制,因为我对此进行了评论,并且单击时图像仍然没有绘制。这是应该绘制图像的触摸开始函数。

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

谁能明白为什么触摸某处时图像不会绘制? touchesBegan 函数在屏幕任意位置被触摸时启动,但图片未显示。感谢您的帮助,我对目标比较陌生-c。

【问题讨论】:

    标签: iphone objective-c ios ipad


    【解决方案1】:

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

    你需要更多这样的东西:

    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 来做一些事情,它包含两个图像的合成。

    【讨论】:

    • 谢谢!我能够获取 newImage 并将其存储在 mainview.h 中声明的 UIImage 与另一个视图中,将加载时的图像设置为仅在溜冰场,然后每次放入圆锥体时更新它。再次感谢。
    猜你喜欢
    • 1970-01-01
    • 2021-12-19
    • 2012-06-15
    • 2012-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多