iOS: Drawing line is appearing behind subviews

2019-05-05 21:07发布

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

2条回答
混吃等死
2楼-- · 2019-05-05 21:39

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
查看更多
地球回转人心会变
3楼-- · 2019-05-05 21:57

Views draw in back-to-front order. If you want something to appear within the subview, the subview has to draw it.

查看更多
登录 后发表回答