In my iOS 5 app I have a custom UIButton
that has a red orb as its image. When the button is tapped I would like the orb to start pulsing/fading between red and green. I have both red and green images and can successfully cross-disolve between the two using the following code:
CABasicAnimation *imageSwitchAnimation = [CABasicAnimation animationWithKeyPath:@"contents"];
imageSwitchAnimation.fromValue = (id)[UIImage imageNamed:@"red.png"].CGImage;
imageSwitchAnimation.toValue = (id)[UIImage imageNamed:@"green.png"].CGImage;
imageSwitchAnimation.duration = 1.5f;
[self.button.imageView.layer addAnimation:imageSwitchAnimation forKey:@"animateContents"];
However, I would like the animation to continue forever (well, until I tell it to stop) and also for the animation to reverse and loop. In other words, fade red -> green -> red and then repeat.
I tried putting the animation block above into an endless loop (together with some logic to determine whether the fading should go from red -> green or green -> red) but this just locks-up the entire app.
Other solutions seem to use Cocos2d, which seems fairly heavy-weight since this is the only animation I need in the app (so I don't want to use such frameworks unless absolutely needed).
Any help would be greatly appreciated.
Yes, you can do this, right within CABasicAnimation
. The trick is that many of its most important methods are not in the CABasicAnimation Class Reference, or even in its superclasses. CABasicAnimation implements a protocol called CAMediaTiming
. See the CAMediaTiming Protocol Reference.
You want to know about two properties in particular: autoreverses
and repeatCount
. Both are self-explanatory, but what if you want infinite repeats? From the entry for repeatCount
:
May be fractional. If the repeatCount is 0, it is ignored. Defaults to 0. If both repeatDuration and repeatCount are specified the behavior is undefined.
Setting this property to HUGE_VALF will cause the animation to repeat forever.
Can you work it out from there?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With