Core Animation CATransformLayer

In the previous post, I showed you how to use the replicator layer class (CAReplicatorLayer). The main problem with layers is that if you want to render them in 3D is quite hard. You need to apply a 3D transformation to each sublayer, fight against the anchor point to get the right transformations. Then, you have to apply a 3D transformation to the root layer and change the m34 value of the 3D transformation matrix to simulate the prospective. If you don’t do that, everything looks flat. Transform layers are the solution to this. So, this time I want to show you another interesting core animation layer that can be used to create a 3D layer hierarchy, rather than the flattened hierarchy rendering model used by other CALayer classes.

To better understand what I am talking about, this video shows what you can do with a CATransformLayer. I created this small animation to let you understand how it works:

This animated cube is obtained using the CATransformLayer class. Here the source code, I used to build the small cube:

You need some defines for this source code. Here, they are:

So, now let’s try to understand what I did. First of all, I created an open face cube: it has only four sides. I leave you as exercise to add the top and bottom side.
The first side I creates is a red square (layer1). I placed it in the center of the transform layer. Nothing new here, right?
The third side (layer3) goes behind the first side at the distance of SQUARE_SIZE points. So, I created again a rectangle and applied to it a translation of -SQUARE_SIZE points. Now, the left (layer4) and right (layer2) sides are similar. They are first rotated 90° with respect to the y axis and then translated to left and to the right, respectively. Finally, they are translated to the back (inside the screen) half SQUARE_SIZE.
Finally, I added the four layers to the transform layer and to make the transformations work correctly I moved the anchorPointZ to the center of the cube. In this way, when you apply any animation to the transform layer everything is transformed correctly.

Now, what happens if we combine the replicator layer from the previous post and this transform layer. Well, here it is an example:

If you liked this post, check here our iOS training classes. You can learn more about these and other advanced topics.

Keep coding,

Geppy

iOS Consulting | INVASIVECODE

iOS Training | INVASIVECODE

(Visited 62 times, 1 visits today)