Graphics Reference
In-Depth Information
▪
You can create the animation using a
CAKeyframeAnimation
, by splitting your
animation into several steps, each with its own timing function (described in the next
section).
▪
You can implement the animation yourself using a timer to update each frame (as
explored in Chapter 11, “Timer-Based Animation”).
Keyframe-Based Easing
To implement our bounce using keyframes, we need to create a keyframe for each
significant point in the easing curve (in this case, the peak and trough of each bounce) and
then apply an easing function that matches up with that segment of the graph. We also need
to specify the time offset for each keyframe using the
keyTimes
property, as the time
between bounces will decrease each time, so the keyframes will not be evenly spaced.
Listing 10.6 shows the code for implementing a bouncing ball animation using this
approach (see Figure 10.6).
Listing 10.6
Implementing a Bouncing Ball Animation Using Keyframes
@interface
ViewController ()
@property
(
nonatomic
,
weak
)
IBOutlet
UIView
*containerView;
@property
(
nonatomic
,
strong
)
UIImageView
*ballView;
@end
@implementation
ViewController
- (
void
)viewDidLoad
{
[
super
viewDidLoad
];
//add ball image view
UIImage
*ballImage = [
UIImage
imageNamed
:
@"Ball.png"
];
self
.ballView = [[
UIImageView
alloc
]
initWithImage
:ballImage];
[
self
.containerView
addSubview
:
self
.ballView];
//animate
[
self
animate
];
}
- (
void
)touchesBegan:(
NSSet
*)touches withEvent:(
UIEvent
*)event
{
//replay animation on tap
[
self
animate
];