Nic*_*ard 4 iphone objective-c uiview 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);
Run Code Online (Sandbox Code Playgroud)
制作另一个自定义视图,它只能绘制线条.将其添加为具有与ImageView相同的框架的子视图,并调用bringSubviewToFront以确保它在前面.您可能需要在自定义视图上设置一些属性opaque = NO,并将背景颜色设置为clear([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
Run Code Online (Sandbox Code Playgroud)