8

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?

Proud Member
  • 40,078
  • 47
  • 146
  • 231

1 Answers1

26

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;
Till
  • 27,559
  • 13
  • 88
  • 122
  • Sorry to be pedantic but a slight correction... UIColor *fromColor = [UIColor redColor]; and UIColor *toColor = [UIColor yellowColor]; (note the asterisks) – amergin Feb 10 '13 at 18:47
  • fromValue and toValue support UIColor, passing CGColor causes crash. – pronebird Oct 07 '13 at 16:44
  • @Andy that is documented where exactly? Apple themselves dont seem to know that - check the example code "Animating Multiple Changes Together" from the [Core Animation Programming Guide](https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/CoreAnimation_guide/CreatingBasicAnimations/CreatingBasicAnimations.html#//apple_ref/doc/uid/TP40004514-CH3-SW1). – Till Oct 09 '13 at 00:55
  • @Till, actually you are right, it doesn't interpolate UIColors. – pronebird Oct 09 '13 at 12:49
  • @Till I used it for custom UIColor property which of course crashed, I guess because animation tried to assign CGColorRef to UIColor property. – pronebird Oct 09 '13 at 13:57