如何为CABasicAnimation设置颜色?

时间:2012-08-18 19:30:15

标签: iphone ios ipad core-animation cabasicanimation

CABasicAnimation具有期望id的toValue属性。但是Quartz Core并不适用于UIColor,它需要一个CGColor结构。我如何为CABasicAnimation提供颜色?

1 个答案:

答案 0 :(得分:24)

只需提供CGColor并将其强制转换为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;

此示例在1秒内将背景颜色从红色淡化为黄色。

直接来自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;