如何通过自定义渐变更改strokeColor

问题描述:

我想动画CAShapeLayer的strokeColor,但在CABasicAnimation中,我有两个值(from和to)。只有两种颜色支持,而动画是火吗?例如,在开始我strokeColor = [UIColor blueColor].CGColor; 然后如何通过自定义渐变更改strokeColor

CABasicAnimation *colorAnimation = [CABasicAnimation animationWithKeyPath:@"strokeColor"]; 
colorAnimation.duration   = 3.0; // "animate over 3 seconds or so.." 
colorAnimation.repeatCount   = 1.0; // Animate only once.. 
colorAnimation.removedOnCompletion = NO; // Remain stroked after the animation.. 
colorAnimation.fillMode = kCAFillModeForwards; 
colorAnimation.toValue = (id)[UIColor redColor].CGColor; 
colorAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]; 

在中途我有一个暗紫色的颜色,但我需要的,例如,黄色。

是否可以向CABasicAnimation添加自定义渐变?

我不认为你可以做到这一点CABasicAnimation,但你可以使用一个CAKeyframeAnimation为动画设置中间值:

CAKeyframeAnimation *colorAnimation = [CAKeyframeAnimation animationWithKeyPath:@"strokeColor"]; 
colorAnimation.values    = @[(id)[[UIColor blueColor] CGColor], 
             (id)[[UIColor yellowColor] CGColor], 
             (id)[[UIColor redColor] CGColor]]; 
colorAnimation.duration    = 3.0; // "animate over 3 seconds or so.." 
colorAnimation.repeatCount   = 1.0; // Animate only once.. 
colorAnimation.removedOnCompletion = NO; // Remain stroked after the animation.. 
colorAnimation.fillMode    = kCAFillModeForwards; 
colorAnimation.timingFunction  = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]; 

如果你想要一个“跨越谱”之类的感觉,你可以这样做:

colorAnimation.values = @[(id)[[UIColor blueColor] CGColor], 
          (id)[[UIColor greenColor] CGColor], 
          (id)[[UIColor yellowColor] CGColor], 
          (id)[[UIColor orangeColor] CGColor], 
          (id)[[UIColor redColor] CGColor]]; 

或者,如果你想要更多的一个简单的蓝色的红色,但避免了真正的暗紫色,你可以这样做:

colorAnimation.values = @[(id)[[UIColor blueColor] CGColor], 
          (id)[[UIColor colorWithRed:0.9 green:0.0 blue:0.9 alpha:1.0] CGColor], 
          (id)[[UIColor redColor] CGColor]]; 

很多选择。

+1

非常非常感谢您的帮助和快速回答! =) – 2013-05-03 20:36:29

+0

@RostK。显然,这会带来很多选择。用另外两个例子更新了我的答案。 – Rob 2013-05-03 20:52:15