使用核心动画来动态改变描边颜色

3
我将尝试动画化CAShapeLayar的strokeColor属性。我查看了文档,文档指出它是一个可动画化的属性。该代码可以用于动画化position.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"];

提前感谢您, Or。
2个回答

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相同的值(它是冗余的)。 此外,我将strokeColorCGColorRef转换为一个id,这正是toValue属性想要的。


3
被接受的答案代码的一个重要缺陷是,addAnimation方法的forKey参数需要是您想要防止触发的隐式动画属性的名称。由于您正在使用CABasicAnimation创建显式动画,因此不希望隐式动画和新创建的显式动画相互干扰。请参考WWDC 2010视频,在第39分钟处查看Session 424核心动画-实践中的核心动画第一部分以进行确认。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接