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:
@implementation MyView
-(id)initWithFrame:(CGRect)frame {
if ((self = [super initWithFrame:frame])) {
imageView = ... // however you create your image view
[self addSubview:imageView];
lineView = [[MyLineView alloc] initWithFrame:imageView.frame];
[self addSubview:lineView];
[self bringSubviewToFront:lineView];
}
return self;
}
...
@end
@implementation MyLineView
-(void)drawRect:(CGRect)rect {
// your drawing code
// remember the coordinate system now has (0, 0) at the top left corner of the
// image view, so adjust your drawing code accordingly
}
@end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With