如何为CABasicAnimation设置颜色?

Pro*_*ber 5 iphone core-animation cabasicanimation ipad ios

CABasicAnimation具有期望id的toValue属性.但是Quartz Core不能与UIColor一起使用,它需要一个CGColor结构.我如何为CABasicAnimation提供颜色?

Til*_*ill 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;
Run Code Online (Sandbox Code Playgroud)

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

另一个例子直接取自Apple的示例代码:

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;
Run Code Online (Sandbox Code Playgroud)