tumbljack

3D Objects in Objective-C with CATransformLayer

Basic Brush Up

So Core Animation is kinda 3D. A CALayer’s transform property takes a CATransform3D struct which is a basic three dimensional transform matrix. You can apply a 3D transform in a few different ways. There a some convenience functions that go something like..


layer.transform = CATransform3DMakeRotation(radian, x, y, z);


or you can access the the transform with a keypath like this..


[layer setValue:[NSNumber numberWithFloat:radian] forKeyPath:@”transform.rotation.x”];


or you can modify the CATransform3D data structure directly by accessing its entries, like m34 is the unique one that applies a perspective projection which you would do like so..


transform.m34 = 1.0 / -zDistance;


So you’ve got 2D objects in 3D space, and a few thousand lines of code later you’ve got a city of album artwork, I guess.  But the whole thing isn’t really 3D. It’s more like 2.5D, cause whereas all your layers can have a 3D transform, you can’t group them together into a 3D object and apply a transform to that, because everything gets flattened. Any CALayer that has a 3D transform applied to it flattens all of it’s sublayers. So you could make a cube, but it would take a lot of code to rotate it, cause you’d have to transform each layer individually and things would quickly get pretty complicated.


The New Hotness

With iPhone OS 3.0 and now OSX 10.6 there are some really awesome additions to the CALayer class hierarchy, so check them out. One of which is CATransformLayer. A transform layer is just a special hosting layer that doesn’t flatten it’s sublayers when a transform is applied to it. So it’s a container layer that can group a bunch of transformed layers into a 3D object that can spin around in space. These can also be stacked, one 3D object inside of another.

I put together a simple example back when the API came out on 3.0.

You can check out the code on GitHub.

The touch interaction uses Bill Dudney’s TrackBall.

And there’s a video of it in action here.


  1. tumbljack posted this
To Tumblr, Love Metalab