如何为 CAShapeLayer 路径和填充颜色设置动画

Posted

技术标签:

【中文标题】如何为 CAShapeLayer 路径和填充颜色设置动画【英文标题】:How to animate CAShapeLayer path and fillColor 【发布时间】:2013-03-27 04:04:18 【问题描述】:

如何为 strokeEnd 设置动画以显示正在绘制的路径?以及如何为填充颜色设置动画?

【问题讨论】:

当你设置它时它会自动动画。你能提供更多关于你想要达到的目标的信息吗? 【参考方案1】:

动画路径

  //setup the CAShapeLayer
myShapeLayer.strokeColor = [[UIColor blueColor] CGColor];
myShapeLayer.lineWidth = 5;
myShapeLayer.fillColor = [[UIColor yellowColor] CGColor];



//Display it!
[self.view.layer addSublayer:myShapeLayer];

//Animate path
CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
pathAnimation.duration = 1.5f;
pathAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
pathAnimation.toValue = [NSNumber numberWithFloat:1.0f];
pathAnimation.repeatCount = 10;
pathAnimation.autoreverses = YES;
[myShapeLayer addAnimation:pathAnimation forKey:@"strokeEnd"];

//Animate colorFill
CABasicAnimation *fillColorAnimation = [CABasicAnimation animationWithKeyPath:@"fillColor"];
fillColorAnimation.duration = 1.5f;
fillColorAnimation.fromValue = (id)[[UIColor clearColor] CGColor];
fillColorAnimation.toValue = (id)[[UIColor yellowColor] CGColor];
fillColorAnimation.repeatCount = 10;
fillColorAnimation.autoreverses = YES;
[myShapeLayer addAnimation:fillColorAnimation forKey:@"fillColor"];

我希望这会有所帮助:)

2021 年更新

斯威夫特

    myShapeLayer.strokeColor = UIColor.blue.cgColor
myShapeLayer.lineWidth = 5
myShapeLayer.fillColor = UIColor.yellow.cgColor

//Display it!
view.layer.addSublayer(myShapeLayer)

//Animate path
let pathAnimation = CABasicAnimation(keyPath: "strokeEnd")
pathAnimation.duration = 1.5
pathAnimation.fromValue = NSNumber(value: 0.0)
pathAnimation.toValue = NSNumber(value: 1.0)
pathAnimation.repeatCount = 10
pathAnimation.autoreverses = true
myShapeLayer.add(pathAnimation, forKey: "strokeEnd")


//Animate colorFill
let fillColorAnimation = CABasicAnimation(keyPath: "fillColor")
fillColorAnimation.duration = 1.5
fillColorAnimation.fromValue = UIColor.clear.cgColor
fillColorAnimation.toValue = UIColor.yellow.cgColor
fillColorAnimation.repeatCount = 10
fillColorAnimation.autoreverses = true
myShapeLayer.add(fillColorAnimation, forKey: "fillColor")

【讨论】:

我要补充一点,fromValue 和 toValue 可以是 CGMutablePathRef 对象,以动画改变路径本身,使用键 @"path"。上面的变化对我的目的有用。谢谢。

以上是关于如何为 CAShapeLayer 路径和填充颜色设置动画的主要内容,如果未能解决你的问题,请参考以下文章

如何为svg rect设置填充颜色

CAShapeLayer 具有边框和填充颜色以及舍入

画布中路径的动画填充颜色

如何为 UIBezierPath 上的填充颜色变化设置动画?

OpenCV:如何为每个像素填充具有每种 RGB 颜色值的 rgb 图像?

UIBezierPath 填充与 CAShapeLayer