iOS:绘图线出现在子视图后面

我有一个简单的UIView,在drawRect中:我添加一个UIImageView作为子视图,然后试图在该子视图上绘制一条线。 但是,这条线在imageview背后被吸引。

我怎样才能使绘图上下文成为子视图,所以我可以在上面绘制?

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

做另一个自定义的视图,唯一的工作就是画线。 将它作为与ImageView相同框架的子视图添加,并调用bringSubviewToFront以确保它在前面。 您可能必须在自定义视图上设置一些属性,例如opaque = NO ,并将背景颜色设置为清除( [UIColor colorWithWhite:0.0 alpha:0.0] )。

顺便说一下,不要在drawRect中添加任何子视图。 drawRect应该只是绘制,而不能改变视图属性或层次结构。 你应该在其他地方添加ImageView和自定义线条图视图,也许在init中。 像这样:

 @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 

视图以前后顺序绘制。 如果你想要在子视图中出现的东西,子视图必须绘制它。