简体   繁体   English

当手指在iPhone上移动时,如何在图像上绘制一条线

[英]How to draw a line on top of an image when finger moves on iPhone

I am trying to draw a line on top of a background image in my UIView tracing the movements of the user's finger. 我试图在UIView的背景图像上方绘制一条线,以跟踪用户手指的运动。 I can accomplish this by drawing the UIImage as my background and then doing my line drawing in drawRect but I have to load the image each time drawRect is called and it makes performance sluggish. 我可以通过绘制UIImage作为背景来完成此任务,然后在drawRect中进行线条绘制,但是每次调用drawRect时都必须加载图像,这会使性能变慢。 Alternatively, if I use a UIImageView as my background image (just adding it to the view in IB or programatically) the lines disappear when it is dragged over the image. 或者,如果我将UIImageView用作背景图像(只需将其添加到IB中或以编程方式添加到视图中),则将其拖到图像上时,线条会消失。 Is there a way to tell the lines to draw on top of the UIImageView. 有没有办法告诉线条画在UIImageView的顶部。 Thanks for your help. 谢谢你的帮助。

Here is my code using the UIImage method: 这是我使用UIImage方法的代码:

- (void)drawRect:(CGRect)rect {
    UIImage *imageField = [UIImage imageNamed:@"field.jpg"];
    CGRect rectForImage=CGRectMake(0,0,200,200);
    [imageField drawInRect:rectForImage];

        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextMoveToPoint(context, x1, y1);
    CGContextAddLineToPoint(context, x2, y2);
    CGContextStrokePath(context);
}

Adding the image as the background view is the correct way to do it. 将图像添加为背景视图是正确的方法。 The problem lies in the fact that you added the image directly to the view. 问题在于您将图像直接添加到视图中。 Subviews are displayed on top of a view, not behind it. 子视图显示在视图的顶部,而不是在视图的后面。 Correctly use a container view that holds the image view as a background, and then your line-drawing view on top of that. 正确使用将图像视图保存为背景的容器视图,然后使用容器视图作为背景。

您可以尝试将(不透明的)线绘制到透明的CALayer上,并将该CALayer放在UIView的顶部,即背景UIImage的上方。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM