Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a color for CABasicAnimation?

CABasicAnimation has the toValue property which expects an id. But Quartz Core doesn't work with UIColor, it wants a CGColor struct instead. How would I supply a color to a CABasicAnimation?

like image 786
Proud Member Avatar asked Aug 18 '12 19:08

Proud Member


1 Answers

Simply provide a CGColor and typecast it towards an id.

UIColor *fromColor = [UIColor redColor];
UIColor *toColor = [UIColor yellowColor];
CABasicAnimation *colorAnimation = [CABasicAnimation animationWithKeyPath:@"backgroundColor"];
colorAnimation.duration = 1.0;
colorAnimation.fromValue = (id)fromColor.CGColor;
colorAnimation.toValue = (id)toColor.CGColor;

This example fades the background color from red to yellow over 1 second.

Another example as taken directly from Apple's example code:

CAKeyframeAnimation* colorAnim = [CAKeyframeAnimation animationWithKeyPath:@"borderColor"];
NSArray* colorValues = [NSArray arrayWithObjects:(id)[UIColor greenColor].CGColor,
            (id)[UIColor redColor].CGColor, (id)[UIColor blueColor].CGColor,  nil];
colorAnim.values = colorValues;
colorAnim.calculationMode = kCAAnimationPaced;
like image 59
Till Avatar answered Sep 30 '22 18:09

Till