7

CABasicAnimation 有 toValue 属性,它需要一个 id。但是 Quartz Core 不能与 UIColor 一起使用,它需要一个 CGColor 结构来代替。如何为 CABasicAnimation 提供颜色?

4

1 回答 1

26

只需提供 aCGColor并将其类型转换为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 示例代码的示例

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;
于 2012-08-18T19:34:17.963 回答