Graphics Reference
In-Depth Information
Note that we've specified blue as both the start and end color in the sequence. That is
necessary because CAKeyframeAnimation does not have an option to automatically use the
current value as the first frame (as we were doing with the CABasicAnimation by leaving
fromValue as nil ). The animation will immediately jump to the first keyframe value when
it begins, and immediately revert to the original property value once it finishes, so for a
smooth animation, we need both the start and end keyframes to match the current value of
the property.
Of course, it's possible to create animations that end on a different value than they begin. In
that case, we would need to manually update the property value to match the last keyframe
before we trigger the animation, just as we discussed earlier.
We've increased the duration of our animation from the default of 0.25 seconds to 2
seconds using the duration property so that the animation doesn't take place too quickly to
follow. If you run the animation, you'll see that the layer cycles through the colors, but the
effect seems a bit... strange. The reason for this is that the animation runs at a constant
pace . It does not slow down as it transitions through each color, and this results in a slightly
surreal effect. To make the animation appear more natural, we will need to adjust the
easing , which will be explained in Chapter 10.
Supplying an array of values makes sense for animating something like a color change, but
it's not a very intuitive way to describe motion in general. CAKeyframeAnimation has an
alternative way to specify an animation, by using a CGPath . The path property allows you
to define a motion sequence in an intuitive way by using Core Graphics functions to draw
your animation.
To demonstrate this, let's animate a spaceship image moving along a simple curve. To
create the path, we'll use a cubic Bézier curve , which is a special type of curve that is
defined using a start and end point with two additional control points to guide the shape.
It's possible to create such a path purely using C-based Core Graphics drawing commands,
but it's easier to do this using the high-level UIBezierPath class provided by UIKit.
Although it's not actually necessary for the animation, we're going to draw the curve
onscreen using a CAShapeLayer . This makes it easier to visualize what our animation is
going to do. After we've drawn the CGPath , we'll use it to create a CAKeyframeAnimation ,
then apply it to our spaceship. Listing 8.6 shows the code, and Figure 8.1 shows the result.
Listing 8.6 Animating a Layer Along a Cubic Bézier Curve
@interface ViewController ()
@property ( nonatomic , weak ) IBOutlet UIView *containerView;
@end
@implementation ViewController
- ( void )viewDidLoad
Search WWH ::




Custom Search