Perspective Transformation of a CALayer
We can achieve beautiful results by 3D transforming a CALayer by various axis. It looks good, but we can make it even better by adding perspective to the transformation.
Usually, A CATransform3D will act as if it’s in a 2D space. let’s animate a CALayer on the Y axis to see what I am talking about:
It looks good. However, here’s the issue. Take a card or any object that resembles the CALayer we animated and rotate it by 180 degrees on the Y-axis while keeping it parallel to your eyes. See any difference?
In the real world, the layer-like object will stay flat and we will perceive it as a rectangle. As the layer starts rotating, one edge will come toward our eyes and we will perceive that edge to be larger than the other. Finally, when the animation will complete, we will again perceive the layer to be a flat rectangle.
Unfortunately, that isn’t happening here. To make it look like a real-world object, we need to create a CATransform3D object and set its m34 property.
Same code as before but this time we changed the m34 property. You can play with the value to get your desired result. Setting a higher divisor will lessen the perspective effect.
Here’s the resulting animation:
Bonus:
Look at the top and bottom edges. They aren’t smooth. To make them smooth change the “shouldRasterize” property of the layer to true and set the “rasterizationScale” scale to device scale.