Graphics Reference
In-Depth Information
Color
Core Animation uses an internal algorithm to calculate animation of color changes.
When you specify a
fromValue
and a
toValue
or
byValue
in a
CABasicAnimation
or an
array of
CGColorRef
values in an array that you provide to the
values
field of a
CAKeyframeAnimation
, Core Animation
determines and fills in all the in
between colors to be used over the dura-
tion of the animation.
NOTE
Tweening
In the world of animation, this is known as
tweening
; where the code looks at the start
and end values and automatically calculates
and runs the values in between.
Listing 2-1 demonstrates how to create a
basic animation that changes the back-
ground color of a layer from red to
green over a period of 5 seconds.
LISTING 2-1
Animating the Background Color from Red to Green
- (
CABasicAnimation
*)backgroundColorAnimation;
{
CABasicAnimation
*anim =
[CABasicAnimation
animationWithKeyPath:
@”backgroundColor”
];
[anim
setDuration
:5.0];
CGColorRef
red =
CGColorCreateGenericRGB
(1.0, 0.0, 0.0, 1.0);
CGColorRef
green =
CGColorCreateGenericRGB
(0.0, 1.0, 0.0, 1.0);
[anim
setFromValue
:(
id
)red];
[anim setToValue:(
id
)green];
CFRelease
(red);
CFRelease
(green);
return
anim;
}
The example code creates a basic animation object,
CABasicAnimation
, using the keypath
backgroundColor
and sets a starting value and ending value using the
-setFromValue
and
-setToValue
parameters. It sets the duration to 5 seconds by calling
-setDuration:5.0
.
When this animation is added to a layer, the layer's background color starts to animate
immediately.
On the iPhone, this code changes slightly as colors are manipulated using the
UIColor
class. Listing 2-2 demonstrates how to create the same animation for the iPhone.