I have a simple UIView, in drawRect: I am adding a UIImageView as a subview, then trying to draw a line on top of that subview. But, the line gets draw behind the imageview.
How can I make the drawing context be the subview so I can draw on top of it?
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 10.0);
CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);
CGContextBeginPath(context);
CGContextMoveToPoint(context, 0, 0);
CGContextAddCurveToPoint(context,125,150,175,150,200,100);
CGContextAddCurveToPoint(context,225,50,275,75,300,200);
CGContextStrokePath(context);
Make another custom view, that has the only job of drawing the line. Add it as a subview with the same frame as the ImageView, and call bringSubviewToFront to make sure it's in front. You might have to set some attributes on your custom view like
opaque = NO
and set the background color to clear ([UIColor colorWithWhite:0.0 alpha:0.0]
).By the way, don't add any subviews in drawRect. drawRect should just draw, not change the view attributes or hierarchy. You should add the ImageView and the custom line drawing view somewhere else, maybe in the init. Like so:
Views draw in back-to-front order. If you want something to appear within the subview, the subview has to draw it.