Iphone iOS:绘图线显示在子视图后面

Iphone iOS:绘图线显示在子视图后面,iphone,objective-c,ios,uiview,Iphone,Objective C,Ios,Uiview,在drawRect中,我有一个简单的UIView:我添加一个UIImageView作为子视图,然后尝试在该子视图的顶部绘制一条线。但是,这条线在imageview后面绘制 如何使绘图上下文成为子视图,以便在其上绘图 CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetLineWidth(context, 10.0); CGContextSetStrokeColorWithColor(context, [UIColor

在drawRect中,我有一个简单的UIView:我添加一个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
,并将背景色设置为清除(
[uicolorWithWhite: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

在我的例子中,线条绘制职责分配到的子视图也处理手势,但不绘制任何内容,不起作用