Search code examples
iosdrawingcore-animationcalayer

How to override drawing order for CALayers when parenting


I'm in a bit of a conundrum. I'd like to stack CALayers in a certain order to draw one over the other, but I'd also like to benefit from the inherited transforms that parenting those layers brings.

Imagine a body, upper arm, forearm, and hand. I'd like to set the anchor points and parent for arm and hand so I can rotate the arm and the hand will follow.

Here's what I do:

CALayer *body = [CALayer layer];
body.path = @"body.png";
body.anchorPoint = ap1;
CALayer *arm = [CALayer layer];
arm.path = @"arm.png";
arm.anchorPoint = ap2;
CALayer *hand = [CALayer layer];
hand.path = @"hand.png";
hand.anchorPoint = ap3;
[myView.layer addSublayer:body];
[myView.layer addSublayer:arm];
[myView.layer addSublayer:hand];
hand.parent = arm;
arm.parent = body;

All well and good, but what if I want the body to overlap the arm and hand? Is there a way to keep this parenting order but override the drawing order? Any clever ideas for doing this?


Solution

  • Sublayers always draw in front of their superlayers. You can't change that.

    Siblings (sublayers of the same superlayer) can use the zPosition property to get finer grained control of the rendering order. By the way, there are some performance implications of having a lot of sublayers, so I'd switch to a more graphics focused framework before you get way too many CALayers going.