This afternoon Thomas Degry (one of my students, www.devine.be) asked how he could program the neat little effect they use in the National Parks iPad app made for National Geographic. If you want to see the effect yourself, I suggest you download the app to check it out. Just select one of the parcs and then tap on the stats or the weather button. You’ll see a nice transition in which the master view ‘steps’ into the background, while the new content is placed in front of it.
It took me a few minutes of tapping to see how the animation works, so here is how you can mimic the effect. Just play with CALayers and some transformations 🙂
The animation looks like this:
The animation is quite easy if you think about it, you will have 2 views:
- the master view, which will ‘step’ backwards
- the detail view, which will overlay the master
First we will animate the parent so it looks like it is stepping backwards. The most important aspect of the animation is that you get the perspective right. There is a little ‘trick’ when using transformations to get this right and that is by setting the .m34 property of your transformation matrix to a very small number (the easy way is by dividing 1 with a large number (like 1 / 500). If you want to learn more about this property, there is an interesting post right here.
CATransform3D trRotate = CATransform3DIdentity;
trRotate.m34 = 1.0 / -500;
SwiftIf you want to avoid clipping troubles with your detail view, you can set the zPosition property to something else.
self.photoView.layer.zPosition = -10;
SwiftThen you need to rotate the picture over its X axis. The amount of degrees you’ll need to figure out yourself. In the demo I use 5 for a subtle animation, but it can be any number you want. Just make sure you convert the degrees to radians. If you forgot to pay attention in geometry class … the formula to go from degrees to radians is
radians = degrees * (PI/180)
SwiftWhen this animation is complete, you want the element to go rotate back. You can do this by setting the transformation matrix back to an identity matrix, or you can scale the element a little bit down so it seems to be a bit smaller. This makes it more realistic. If you want to add that extra feeling of ‘inactivity’, you can fade out the element.
In the completion handler of the first animation block, you start a new animation block.
[UIView animateWithDuration:0.2 animations:^{
self.photoView.alpha = .5;
self.photoView.transform = CGAffineTransformMakeScale(0.8, 0.8);
}];
SwiftAnd that is! If you want to restore the element you just do the same animation with reversed values!
I’ve put the code on GitHub, so you can check it out for yourself!