I want to create a CALayer animation that gives sort of a 'flashy' effect. For that I'm trying to animate the 'opacity' property, but my problem is that I have no idea where to start and how to do it.
Here is a graphical explanation of the animation:
opacity
| ___
1 | | |
| | | * repeatCount
0 |___| |_ . . .
-------------------------> time
|______|
duration
The opacity starts at 0, then animates to 1, then to 0 again (this 0-to-1-to-0 animation takes a number of seconds equal to duration). Then this process is repeated 'repeatCount' times.
Here's some background on the code:
float duration = ...; // 0.2 secs, 1 sec, 3 secs, etc
int repeactCount = ...; // 1, 2, 5, 6, ect
CALayer* layer = ...; // I have a CALayer from another part of the code
layer.opacity = 0;
// Animation here
done = YES; // IN THE END of the animation set this ivar to yes
What is the best way to accomplish this? I have never used CALayers before, so this is also a good opportunity to learn how their animation system works. By the way, I have searched the docs and I understand how you add one or two simple animations, but I have no idea how to do this particular one.
The best way to accomplish this is to use an explicit animation (see guide) by creating an instance of CABasicAnimation
and adding it to the layer.
The code would look something like this:
CABasicAnimation *flash = [CABasicAnimation animationWithKeyPath:@"opacity"];
flash.fromValue = [NSNumber numberWithFloat:0.0];
flash.toValue = [NSNumber numberWithFloat:1.0];
flash.duration = 1.0; // 1 second
flash.autoreverses = YES; // Back
flash.repeatCount = 3; // Or whatever
[layer addAnimation:flash forKey:@"flashAnimation"];
If you want to know when the animation is done you can set a delegate and implement the animationDidStop:finished:
method, however it's best to use a completion block as that allows all the code to be in the same place. If you are writing for iOS 4 or OS X then you can use the excellent CAAnimationBlocks category to accomplish this.
Trojanfoe's answer is excellent. I just want to add that if you want more control over the "timeline" (how long should it take to fade out? how long should we then wait? then how long should it take to fade in? and so on) you're going to want to combine multiple CABasicAnimation
s into a CAAnimationGroup.
You might want to read my book chapter on this topic, the last part of which constitutes a tutorial on CAAnimation and its offspring:
http://www.apeth.com/iOSBook/ch17.html#_core_animation
Note that my discussion is directed at iOS; on Mac OS X, if that's where you are, the view/layer architecture is a little different, but what it says about CAAnimation is still correct.