Graphics Reference
In-Depth Information
NSTimer
Actually, we already did something like that in Chapter 3, “Layer Geometry,” with the
clock example, when we used an
NSTimer
to animate the hand movement. In that example,
the hand only updated once per second, but the principle is really no different if we speed
up the timer to fire 60 times per second instead.
Let's try modifying the bouncing ball animation from Chapter 10 to use an
NSTimer
instead
of a
CAKeyframeAnimation
. Because we will now be calculating the animation frames
continuously as the timer fires (instead of in advance), we need some additional properties
in our class to store the animation's
fromValue
,
toValue
,
duration
, and the current
timeOffset
(see Listing 11.1).
Listing 11.1
Implementing the Bouncing Ball Animation Using
NSTimer
@interface
ViewController ()
@property
(
nonatomic
,
weak
)
IBOutlet
UIView
*containerView;
@property
(
nonatomic
,
strong
)
UIImageView
*ballView;
@property
(
nonatomic
,
strong
)
NSTimer
*timer;
@property
(
nonatomic
,
assign
)
NSTimeInterval
duration;
@property
(
nonatomic
,
assign
)
NSTimeInterval
timeOffset;
@property
(
nonatomic
,
strong
)
id
fromValue;
@property
(
nonatomic
,
strong
)
id
toValue;
@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
];