Search code examples
iosquartz-corecatransform3d

How to properly set the perspective in CATransform3D


I'm starting to play with CATransform3D and I'm getting most of the stuff. But one thing I don't understand is the perspective. I know it's the m34 and I know how it changes the result, but I don't quite get it how to obtain the ideal value for my case. It's by trial and error, or there's an analytic way to calculate it?

There's this project, 3DTransformFun, I would like to mention that helped me a lot building my transforms.


Solution

  • I'm glad you've found 3DTransformFun helpful! In there there's a default perspective of -1/500, IIRC, though obviously you can mess with this by supplying a manual transform.

    The value's effect on perspective is related to 1 / the distance (or more commonly, -1 / the distance) the "camera" is from the layer, as mentioned in this answer. If you set it to anything other than a small value, this suggests the camera is right next to the layer, and you get crazy distortions. Set to a tiny or zero value, and the camera is too far from the layer to show any perspective.

    In my experience there's no "correct" perspective to apply. It depends on the effect you're after, so trial and error is the way to go. However, knowing the -1/distance trick (typically using around the width of the scene as a starting point) gives you a good starting point.