Using Core animation to animate StrokeColor

£可爱£侵袭症+ 提交于 2019-12-31 02:07:22

问题


I'm trying to animate CAShapeLayar's strokeColor property. I looked throught the documentation and it was stated that it is an animatable property. The code is working for animating postion.y but not the the strokeColor. I'll be happy to get any kind of help or advice

The code I've used:

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"];

Thanks in advance, Or.


回答1:


This should work, as I just tested it:

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.

Notice I removed the fromValue property line from the animation, since you want the same value as you set the strokeColor before the animation (its redundant). Also, I casted the strokeColor's CGColorRef to an id, which is exactly what the toValue property wants.




回答2:


An important pitfall of the accepted answer code is that the forKey: parameter of the addAnimation method needs to be the name of the property whose implicit animation you want to prevent from firing. Since you are creating an explicit animation with CABasicAnimation, you don't want both the implicit animation and the newly-created explicit animation from interfering with one another. Refer to the WWDC 2010 video for Session 424 Core Animation - Core Animation in Practice, Part 1 at the 39 minute mark for confirmation.



来源:https://stackoverflow.com/questions/7080952/using-core-animation-to-animate-strokecolor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!