Search code examples
iosobjective-ccocoa-touchcalayercgcontext

How to draw inside a layer and add to context only after [viewLayer addSublayer:newLayer]?


The question

How do you create a separate context for your layer and incorporate that context into super layer?

Why I want to do this

I want abstract the drawing of a view layers into separate objects/files. I want to construct a view out of layers, then position then on top of one another and have other possibilities as that.

The problem is that I'm not aware of you you're supposed to draw a part of your view into a layer without drawing straight into the context of the main views sublayer.

Here's an example, I have subclassed CALayer with HFFoundation:

@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

Now when I instantiate my custom layer inside a views (void)drawRect:(CGRect)rect I this way:

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

I get this result (no drawings appear, just the bg color inside the layer frame):

adding a sublayer

If I [foundation drawLayer:foundation inContext:context]; afterwards, the drawing appears, but it appears inside the top layers context, not in foundation layer. Since foundation layer is also lower in the hierarchy, it hides the drawing (unless I reduce it's alpha, which I've dont in the picture):

it draws straight into the context

How do you draw into the layer itself, I.e. foundation in this case?


Solution

  • To insert a sublayer and set its index you want this piece of code:

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