Using CABasicAnimation
At this point, you have already seen the CABasicAnimaion object in action. In this section, however, we consider in detail how to take advantage of this class and basic animations.
Basic animation as implemented using the CABasicAnimation class animates a layer property between two values, a starting and an ending value. To move a layer from one point to another in its containing window, for example, we can create a basic animation using the keypath position. We give the animation a start value and an ending value and add the animation to the layer. The animation begins immediately in the next run loop. Listing 3-8 demonstrates how to animate the position of a layer.
Listing 3-8. Animate the Layer Position
- (IBAction)animate:(id)sender; { CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"]; [animation setFromValue:[NSValue valueWithPoint:startPoint]]; [animation setToValue:[NSValue valueWithPoint:endPoint]]; [animation setDuration:5.0]; [layer addAnimation:animation forKey:@"position"]; }
This code moves the position of a layer from startPoint to endPoint. These two values are NSPoint objects. The position property is the center point of the layer. It is set relative to its containing layer.
If you add this listing to your project we created in the previous section, you simply connect a button to the action in Interface Builder. To do so, follow these steps:
- Open AppDelegate.h and add an action declaration, as follows:
@interface AppDelegate : NSObject { IBOutlet NSWindow *window; CALayer *layer; } - (IBAction)animate:(id)sender;
- Open AppDelegate.m and add the animate implementation code provided in Listing 3-8.
- Open Interface Builder. From the Objects Library, drag a button onto the main window.
- Control-click the button you just dragged on the main window and drag a connection to the AppDelegate object. Select the animate action.
- Return to Xcode and Build and Go to see this animation run.
That's it. That is really all there is to animating a layer. You create the animation, set the to and from values, set a duration (which is optional as the default 0.25 seconds will be used if you don't specify a duration explicitly), and add the animation to the layer you want to animate.
That being said, you will not likely leave it at that because the details of implementation add nuance and complexity. For example, the first time you run the animation from Listing 3-8, you notice that while your layer animates to the correct position in the parent view using the duration you specified, when the animation completes, it jumps right back to its starting position. Is this a bug? How can we fix it? We get to that next.
Animating Versus Setting Layer Properties
When you create your CABasicAnimation, you need to specify a start and stop value for the animation using the calls to –setFromValue and –setToValue respectively. When you add your basic animation to a layer, it runs. However, when the property animation finishes, in the case of animating the position property, the layer snaps right back to its starting position.
Remember that when animating, you use at least two objects. These objects are the layer itself, a CALayer or CALayer-derived object, and the animation that you assign to it—the CABasicAnimation object in our previous examples. Just because you have set a final value (destination) for your animation object does not mean that the layer property being animated assumes this value when the animation has finished. You must explicitly set the layer's property so that when the animation has finished, the property you animated will actually be set in the layer to the to-value you specified.
You can simply cause your animation to stop at the end point you specify, but this is only a visible stickiness, if you will. The internal value is still the same. To actually change the internal model value, you have to explicitly set the property in question. For example, to explicitly set the position property, you need to call –setPosition on the layer. This creates a little problem, though.
If you set the value of a property by calling -set on that property explicitly, the default animation will be used rather than one you might set for the property you are animating. Listing 3-9 demonstrates one way you might try to set the position. Notice that we have created a basic animation to use for the position property; however, the explicit call to –setPosition on the layer overrides the animation we set in the line that follows it, making the basic animation completely useless. If you try this code, you see that although our layer ends up in the right position, it uses the default duration of 0.25 seconds rather than the 5 seconds we have explicitly set in the animation.
Listing 3-9. Animating and Updating the Position Property
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"]; [animation setFromValue:[NSValue valueWithPoint:startPoint]]; [animation setToValue:[NSValue valueWithPoint:endPoint]]; [animation setDuration:5.0]; [layer setPosition:endpoint]; [layer addAnimation:animation forKey:nil];
So now the question becomes, how can you get the animation to use the specified duration? Take a look at the last line in Listing 3-9. Notice that the forKey: parameter of the call is set to nil. This is the reason why the animation is not overriding the default. If you change the last line to [layer addAnimation:animation forKey:@"position"], the animation will work using the duration as expected. This tells the layer to use the new animation we have specified for this keypath whenever it needs to be animated.
Implicit Layer Animation and the Default Timing Function
We can use the CATransaction class to override the default duration as we previously did in this chapter, and it does make it simple to animate the layer using the duration we specify. If we use the code in Listing 3-10, the position property is set in the layer and the property is animated on its way there as you might expect.
Listing 3-10. Overriding the Default Duration for Implicit Animation
[CATransaction begin]; [CATransaction setValue:[NSNumber numberWithFloat:5.0] forKey:kCATransactionAnimationDuration]; [layer setPosition:endPoint]; [CATransaction commit];
However, when you run this code, you see that although it animates the position over a five second duration, it also applies the default media timing function that is kCAMediaTimingFunctionEaseInEaseOut. This function causes the animation to start slowly and then speed up only to slow down again as it approaches its destination. This functionality is fine if that is the media timing function you want, but if you want it to be linear (kCAMediaTimingFunctionLinear), for example, you need to consider another way. And there is no apparent way to set the default media timing function for implicit animations.
This means that if you want to use any other timing function than the default, you have to use explicit animation, as shown in Listing 3-9.
Visual Stickiness
Another approach we might take is to set several properties in our animation object that cause the animation to be sticky when it finishes. In other words, the layer will appear to be at the destination value. The stickiness in this scenario, however, is visual only, which is to say that the underlying value of the layer property, position continues to be the value the position was when the animation started. This is a fine approach if you don't need the internal value to be updated. Listing 3-11 shows how to implement this method, making the layer stick at the end of its duration.
Listing 3-11. Making the Layer Position Sticky
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"]; [animation setToValue:[NSValue valueWithPoint:endPoint]]; [animation setDuration:5.0]; [animation setFillMode:kCAFillModeForwards]; [animation setRemovedOnCompletion:NO]; [layer addAnimation:animation forKey:@"position"];
We need to set two animation properties for the layer to stay at the destination position. First is the fill mode. We tell it to anchor the animation value to the final value by calling –setFillMode, passing it the constant kCAFillModeForwards. Then we must tell the animation not to remove itself from the layer's array of animations when the animation completes by calling –setRemovedOnCompletion passing it NO.