如何在[view Layer addSublayer:new Layer]之后在一个图层内绘制并添加到上下文?

时间:2013-05-10 10:26:59

标签: ios objective-c cocoa-touch calayer cgcontext

问题

如何为图层创建单独的上下文并将该上下文合并到超级图层中?

为什么我要这样做

我希望将视图图层的绘制抽象为单独的对象/文件。我想用层构建一个视图,然后将它们放在另一个上面并有其他可能性。

问题是我不知道你应该将你的视图的一部分绘制到一个层中,而没有直接绘制到主视图子层的上下文中。

以下是一个示例,我已将CALayerHFFoundation子类化:

@implementation HFFoundation

- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx {
    UIBezierPath *foundation = [UIBezierPath bezierPath];
    // some drawing goes on here in the form of messages to [foundation]
}

@end

现在,当我在视图(void)drawRect:(CGRect)rect中实例化我的自定义图层时,我就是这样:

HFFoundation *foundation = [HFFoundation new];
foundation.frame = CGRectMake(40, viewHeight - 100, 300, 100);
foundation.backgroundColor = [[UIColor colorWithRed:1 green:.4 blue:1 alpha:0.2] CGColor];

[self.window.rootViewController.view.layer addSublayer:foundation];

我得到了这个结果(没有图画出现,只是图层框内的bg颜色):

adding a sublayer

如果之后我[foundation drawLayer:foundation inContext:context];,则会显示图形,但它会显示在顶层上下文中,而不是foundation图层中。由于foundation层在层次结构中也较低,因此它隐藏了绘图(除非我减少它的alpha,我在图片中没有):

it draws straight into the context

你如何画入图层本身,即。在这种情况下foundation

1 个答案:

答案 0 :(得分:1)

要插入子图层并设置其索引,您需要这段代码:

[view.layer insertSublayer:foundation atIndex:0];