Search code examples
iphoneiosdrawingcore-animation

Why is my 3-D rotated image intersecting another image?


I am making an application where I need to transform images, and images can be placed anywhere in the view. But the problem I am facing when I am doing perspective transformation using below code

CATransform3D rotationAndPerspectiveTransform = self.layer.transform;
rotationAndPerspectiveTransform = CATransform3DRotate(rotationAndPerspectiveTransform, 22.5f * M_PI / 180.0f, 0, 1, 0.0f);
self.layer.transform = rotationAndPerspectiveTransform;

It works perfectly, but when I try to place a 2D image over the "perspective transformed" image(3D), the 2D image intersects the 3D image. It doesn't appear above the 3D image.

Why is this happening?


Solution

  • If two CALayers are siblings, they exist in the same 3-D space. When you rotate the one layer like you do above (which I'm guessing you drew from my older answer, although without the perspective portion of that code), you do so about its anchor point.

    By default, that anchor point is the center of the layer, so that layer is split by the 0 Z plane. Half of it is below 0 and half above 0.

    When you create a new layer as a sibling of the original one, it is positioned at a Z coordinate of 0 and thus will intersect the center of your rotated layer. To place that layer above your existing one, you can set the zPosition property of the new layer to be a large enough positive (or possibly negative, I keep getting this mixed up) value to have the entire layer hover above the rotated one.

    Another possibility is to place the layer you wish to be in front of the rotated one as a sibling of the rotated layer's superlayer. The layer hierarchy is obeyed first, before any 3-D positioning of sibling layers.