iOS:绘图线出现在子视图后面 [英] iOS: Drawing line is appearing behind subviews

查看:50
本文介绍了iOS:绘图线出现在子视图后面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在drawRect中,我有一个简单的UIView:我将UIImageView添加为子视图,然后尝试在该子视图的顶部绘制一条线.但是,这条线在imageview后面绘制.

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

推荐答案

进行另一个自定义视图,该视图的唯一工作是绘制线条.将其添加为与ImageView具有相同框架的子视图,然后调用BringSubviewToFront以确保它在前面.您可能必须在自定义视图上设置一些属性,例如opaque = NO,并将背景颜色设置为清除([UIColor colorWithWhite:0.0 alpha:0.0]).

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]).

顺便说一句,不要在drawRect中添加任何子视图. drawRect应该仅绘制,而不更改视图属性或层次结构.您应该在其他位置(可能是在init中)添加ImageView和自定义线条绘图视图.像这样:

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

这篇关于iOS:绘图线出现在子视图后面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆