Graphics Reference
In-Depth Information
- (
void
)viewDidLoad
{
[
super
viewDidLoad
];
//add the ship
CALayer
*shipLayer = [
CALayer
layer
];
shipLayer.
frame
=
CGRectMake
(
0
,
0
,
128
,
128
);
shipLayer.
position
=
CGPointMake
(
150
,
150
);
shipLayer.
contents
= (
__bridge
id
)[
UIImage
imageNamed
:
@"Ship.png"
].
CGImage
;
[
self
.containerView.
layer
addSublayer
:shipLayer];
//animate the ship rotation
CABasicAnimation
*animation = [
CABasicAnimation
animation
];
animation.
keyPath
=
@"transform"
;
animation.
duration
=
2.0
;
animation.
toValue
= [
NSValue
valueWithCATransform3D
:
CATransform3DMakeRotation
(
M_PI
,
0
,
0
,
1
)];
[shipLayer
addAnimation
:animation
forKey
:
nil
];
}
@end
This works, but it turns out that this is more by luck than design. If we were to change the
rotation value from
M_PI
(180 degrees) to
2 * M_PI
(360 degrees) and run the animation,
we'd find that the ship doesn't move at all. That's because the matrix representation for a
rotation of 360 degrees is the same as for 0 degrees, so as far as the animation is concerned,
the value hasn't changed.
Now try using
M_PI
again, but set it as the
byValue
property instead of
toValue
, to indicate
that the rotation should be
relative
to the current value. You might expect that to have the
same effect as setting
toValue
, because 0 + 90 degrees == 90 degrees, but in fact the ship
image
expands
instead of rotating because transform matrices cannot be added together like
angular values can.
What if we want to animate the translation or scale of the ship independently of its angle?
Because both of those require us to modify the
transform
property, we would need to
recalculate the combined effect of each of those animations at each point in time and create
a complex keyframe animation from the combined transform values, even though all we
really want to do is animate a few conceptually discrete attributes of our layer
independently.
Fortunately, there is a solution: To rotate the layer, we can apply our animation to the
transform.rotation
key path instead of animating the
transform
property itself (see
Listing 8.9).