Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
Chapter 7 Layers Like an Onion: Core Animation The iPhone has made animation central to the mobile experience. Views slide in and out, applications zoom into place, pages fly into the bookmark list. Apple has made animation not just a beautiful part of the experience, but a better way to let the user know what's happening and what to expect. When views slide into place from right to left, it is natural to press the left-pointing button to go back to where you were. When you create a bookmark and it flies to the toolbar, it's more obvious where you should look to get back to that bookmark. These subtle cues are a critical part of making your user interface intuitive as well as engaging. To facilitate all this animation, iOS devices include a powerful GPU and frameworks that let you harness that GPU easily. In this chapter you discover the two main animation systems of iOS: view animations and the Core Animation framework. You learn how to draw with Core Animation layers and how to move layers around in two and three dimensions. Common decorations like rounded corners, colored borders, and shadows are trivial with CALayer, and you learn to apply them quickly and easily. You learn how to create custom automatic animations, including animating your own properties. Finally, Core Animation is all about performance, so you learn how to manage layers in multithreaded applications. This chapter focuses on animations for view-based programming. These frameworks are ideal for most iOS applications except games. Game development is outside the scope of this book, and is usually best served by built-in frameworks like OpenGL ES or third-party frameworks like Cocos2D. For more information on OpenGL ES, see the OpenGL ES for iOS portal at developer.apple.com. For more information on Cocos2D, see cocos2d-iphone.org. View Animations UIView provides rich animation functionality that is very easy to use and well optimized. Most common animations can be handled with +animateWithDuration:animations: and related methods. You can use UIView to animate frame, bounds, center, transform, alpha, backgroundColor, and contentStretch. Most of the time you'll animate frame, center, transform, and alpha. It's likely that you are familiar with basic view animations, so I'll just touch on the high points in this section and then move on to more advanced layer-based drawing and animation. Let's start with a very simple animation of a ball that falls when you tap the view. CircleView just draws a circle in its frame. The following code creates the animation shown in Figure 7-1.