Graphics Reference
In-Depth Information
CGFloat red = arc4random () / ( CGFloat ) INT_MAX ;
CGFloat green = arc4random () / ( CGFloat ) INT_MAX ;
CGFloat blue = arc4random () / ( CGFloat ) INT_MAX ;
UIColor *color = [ UIColor colorWithRed :red
green :green
blue :blue
alpha : 1.0 ];
//create a basic animation
CABasicAnimation *animation = [ CABasicAnimation animation ];
animation. keyPath = @"backgroundColor" ;
animation. toValue = ( __bridge id )color. CGColor ;
//apply animation to layer
[ self .colorLayer addAnimation :animation forKey : nil ];
}
@end
When we run the example, it doesn't work as expected. Tapping the button causes the layer
to animate to a new color, but it then immediately snaps back to its original value.
The reason for this is that animations do not modify the layer's model , only its presentation
(see Chapter 7). Once the animation finishes and is removed from the layer, the layer
reverts back to the appearance defined by its model properties. We never changed the
backgroundColor property, so the layer returns to its original color.
When we were using implicit animation before, the underlying action was implemented
using a CABasicAnimation exactly like the one we have just used. (You might recall that in
Chapter 7, we logged the result of the -actionForLayer:forKey: delegate method and
saw that the action type was a CABasicAnimation .) However, in that case, we triggered the
animation by setting the property. Now we are performing the same animation directly, but
we aren't setting the property any more (hence the snap-back problem).
Assigning our animation as a layer action (and then simply triggering the animation by
changing the property value) is by far the easiest approach to keeping property values and
animation states in sync, but assuming that we cannot do that for some reason (usually
because the layer we need to animate is a UIView backing layer), we have two choices for
when we can update the property value: immediately before the animation starts or
immediately after it finishes.
Updating the property before the animation has started is the simpler of those options, but it
means that we cannot take advantage of the implicit fromValue , so we will need to
manually set the fromValue in our animation to match the current value in the layer.
Search WWH ::




Custom Search