Search code examples
ios3dcore-animationtransform

How to move CALayers along the z-Axis and apply perspective


I've got a main CALayer which contains a few sublayers. I rotated the main layer by 89 degrees around the x-Axis, so I'm barely seeing it (it's close to being a slice in the middle of the screen now).

CATransform3D moveToOrigin = CATransform3DMakeTranslation(-self.bounds.size.width / 2.0f, -self.bounds.size.height / 2.0f, 0.0);
CATransform3D rotateX = CATransform3DConcat(moveToOrigin, CATransform3DMakeRotation(DEGREES_TO_RADIANS(89.0), 1.0, 0.0, 0.0));
CATransform3D finalTransform = CATransform3DConcat(rotateX, CATransform3DMakeTranslation(self.bounds.size.width / 2.0f, self.bounds.size.height / 2.0f, 0.0));

mainLayer.transform = finalTransform;

Now I want to move each sublayer along the z-Axis, so that it looks like a stack with spacing between the layers. Unfortunately, all I see is all sublayers flat on the main layer.

for (int i = 0; i < self.sublayers.count; i++) {
    CALayer *aLayer = _layers[i];
    transform = CATransform3DMakeTranslation(0.0, 0.0, 100 * i);
}

The weird thing is that moving along the x or y Axis works like a charm. Does it have something to do with that sublayer transform?

Is changing the zPosition property the same as moving the layer with CATransform3D along the z-axis?


Solution

  • When layers are rendered they are generally being flattened so even though they may contain sublayers with different Z values, the rendered layer is going to be flat. However, there is one layer class which doesn't have this behavior and it is called CATransformLayer. It doesn't do have any contents of its own but it also leaves the sublayers intact.