Graphics Reference
In-Depth Information
As you might suspect, we can also animate properties of a layer explicitly. To achieve the
exact same effect as we did with the code in Listing 3-6, we can instead use the code in
Listing 3-7.
LISTING 3-7
Explicitly Animating the Layer Bounds Property
CABasicAnimation
*boundsAnimation = [
CABasicAnimation
animationWithKeyPath
:
@”bounds”
];
[boundsAnimation
setFromValue
:[
NSValue
valueWithRect:oldRect]];
[boundsAnimation setToValue:[
NSValue
valueWithRect:newRect]];
[boundsAnimation
setDuration
:5.0f];
[layer
setBounds
:NSRectToCGRect(newRect)];
[layer
addAnimation
:boundsAnimation
forKey
:
@”bounds”
];
NOTE
Notes on Frame Animation
You might have noticed in the layer example code, we are calling
-setBounds
rather than
-setFrame
. It is common to want to move a layer around its containing view, which causes
many first-time Core Animation programmers to attempt to use
frame
as the keypath for layer
resizing. As you will quickly learn, however, animating the
frame
itself won't work. The
frame
field of the layer is a derived value—calculated from the
position
,
bounds
,
anchorPoint
,
and
transform
properties. This means that although you can set the
frame
explicitly, it will
not animate. This is not a problem though. You just need to determine whether you want to
move
the
frame
or
resize
the
frame
. If you want to animate the size of the layer's rectangle,
use
bounds
as your keypath. If you want to move the frame, use
position
as your keypath.
If you want to move
and
resize the layer at the same time, create two animations, one to
animate the
bounds
and one to animate the
position
.
In Listing 3-6, we used the
CABasicAnimation
class, the primary animation object for
basic animation. We take a deeper look at it shortly, but first we are going to set up a
simple Xcode project to demonstrate basic layer animation.
The first thing you want to do when you create a Core Animation based project is to
make sure the root layer of your view is layer backed. Let's walk through creating a Core
Animation-based project and set up the root layer on OS X.