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. 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. 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. Is there a way to tell the lines to draw on top of the UIImageView. Thanks for your help.

Here is my code using the UIImage method:

- (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);


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.

You can try drawing your (opaque) lines to a transparent CALayer, and placing that CALayer on top of your UIView, thus above the background UIImage.

Need Your Help

How do you develop a website in a team?

tfs process teamwork

We are building a website, which is serving only asmx-webservices. These webervices are consumed by Windows Mobile clients.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.