CALayer drawInContext vs addSublayer

How can I use both of these options in the same UIView correctly?

I have one custom subclass of CALayer in which I draw a template in drawInContext

I have another one in which I set the PNG overlay image as content.

I have a third, which is just a background.

How do I overlay all 3 of these elements?

[self.layer addSublayer:bottomLayer];    // this line is the problem

[squaresLayer drawInContext:viewContext];
[self.layer addSublayer:imgLayer];

The other 2 themselves draw correctly if I do them in this order. No matter where I try to set the bottom layer, it always prevents squaresLayer from drawing. The reason I need 3 layers is because I intend to animate colors in the background and custom layers. The top layer is just a graphic overlay.

+3
1

, - CALayers,

- (void)drawRect:(CGRect)rect {

    [imgLayer removeFromSuperlayer];

    CGFloat w = [self.blockViewDelegate w];
    CGFloat h = [self.blockViewDelegate h];

    CGFloat wb = w/4;
    CGFloat hb = h/4;

    CGContextRef viewContext = UIGraphicsGetCurrentContext();

    // Layers

    [bottomLayer sizes:wb :hb :1];
    bottomLayer.frame = CGRectMake(0, 0, w, h);
    bottomLayer.opaque = NO;

    [topLayer sizes:wb :hb :0];
    topLayer.frame = CGRectMake(0, 0, w, h);
    topLayer.opaque = NO;

    // Overlay

    imgLayer.frame = CGRectMake(0, 0, w, h);
    imgLayer.opaque = NO;
    imgLayer.opacity = 1.0f;

    UIImage *overlay = [self.blockViewDelegate image];
    CGImageRef img = overlay.CGImage;
    imgLayer.contents = (id)img;

    // Add layers

    [bottomLayer drawInContext:viewContext];
    [topLayer drawInContext:viewContext];
    [self.layer addSublayer:imgLayer];

}

blockViewDelegate - , , UIView.

topLayer bottomLayer UIView, . "setNeedsDisplay" , , .

+1

Source: https://habr.com/ru/post/1714112/


All Articles