Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CALayer opacity animation

Tags:

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.

like image 335
Alex Avatar asked Sep 16 '12 17:09

Alex


1 Answers

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.

like image 160
trojanfoe Avatar answered Sep 21 '22 03:09

trojanfoe