使用Core动画为StrokeColor设置动画

时间:2011-08-16 15:41:43

标签: ios core-animation core-graphics

我正在尝试为CAShapeLayar的strokeColor属性设置动画。我查看了文档,并声明它是一个可动画的属性。该代码用于动画postion.y但不是strokeColor。我很乐意得到任何帮助或建议

我用过的代码:

lyr.fillColor = [[UIColor clearColor] CGColor];
lyr.lineWidth = 3.8;
lyr.strokeColor = [[UIColor yellowColor] CGColor];
lyr.position = CGPointMake(160, 431);
lyr.anchorPoint = CGPointMake(.5f, .5f);
[self.view.layer addSublayer:lyr];

CABasicAnimation *basicAnimation = [CABasicAnimation animationWithKeyPath:@"strokeColor"];
basicAnimation.fromValue = [lyr valueForKey:@"strokeColor"];



basicAnimation.toValue =[NSValue valueWithPointer:[[UIColor clearColor] CGColor]];


basicAnimation.duration = 2;
basicAnimation.repeatCount = 10;
basicAnimation.autoreverses = YES;
[lyr addAnimation:basicAnimation forKey:@"strokeColor"];

提前致谢, 或

2 个答案:

答案 0 :(得分:6)

这应该可行,正如我刚刚测试过的那样:

CABasicAnimation *strokeAnim = [CABasicAnimation animationWithKeyPath:@"strokeColor"]; // I changed the animation pointer name, but don't worry.
basicAnimation.toValue = (id) [UIColor clearColor].CGColor; // Just get rid of the fromValue line, and just cast the CGColorRef to an id.
basicAnimation.duration = 2;
basicAnimation.repeatCount = 10;
basicAnimation.autoreverses = YES;
[lyr addAnimation:strokeAnim forKey:@"flashStrokeColor"]; // I like to name this key differently, so as not create confusion.

注意我从动画中删除了fromValue属性行,因为您需要与在动画之前设置strokeColor相同的值(冗余)。 另外,我将strokeColor的CGColorRef转换为id,这正是toValue属性所需要的。

答案 1 :(得分:3)

接受的答案代码的一个重要缺陷是addAnimation方法的forKey:参数需要是要阻止其触发的隐式动画的属性的名称。由于您使用CABasicAnimation创建显式动画,因此您不希望隐式动画和新创建的显式动画相互干扰。请参阅WWDC 2010 video会话424核心动画 - 实践中的核心动画,第1部分,在39分钟标记处进行确认。