【问题标题】:iOS: Drawing line is appearing behind subviewsiOS:绘图线出现在子视图后面
【发布时间】:2011-08-23 21:25:39
【问题描述】:

我有一个简单的 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);

【问题讨论】:

    标签: iphone objective-c ios uiview


    【解决方案1】:

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

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

    @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
    

    【讨论】:

    • 分配了线条绘制职责的子视图在我的情况下也处理手势但什么也没画,不起作用
    【解决方案2】:

    视图按从后到前的顺序绘制。如果您希望某些内容出现在子视图中,则子视图必须绘制它。

    【讨论】:

      猜你喜欢
      • 2011-02-08
      • 2021-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-07
      • 2011-01-15
      • 2018-03-23
      相关资源
      最近更新 更多