【发布时间】:2018-06-13 05:31:19
【问题描述】:
我正在尝试使用CAShapeLayer 和动画UIBezierPath 在Swift 4 中创建一个圆形进度条。这很好用,但我希望圆圈在动画达到某个值后将其更改为 strokeColor。
例如:当圆圈画完 75% 后,我想将 strokeColor 从 UIColor.black.cgColor 切换到 UIColor.red.cgColor。
我的圆圈和“进度”动画的代码如下所示:
let circleLayer = CAShapeLayer()
// set initial strokeColor:
circleLayer.strokeColor = UIColor.black.cgColor
circleLayer.path = UIBezierPath([...]).cgPath
// animate the circle:
let animation = CABasicAnimation()
animation.keyPath = #keyPath(CAShapeLayer.strokeEnd)
animation.fromValue = 0.0
animation.toValue = 1
animation.duration = 10
animation.isAdditive = true
animation.fillMode = .forwards
circleLayer.add(animation, forKey: "strokeEnd")
我知道也可以为strokeColor 键路径创建一个CABasicAnimation,并将fromValue 和toValue 设置为UIColors 以使strokeColor 慢慢改变。但这就像随着时间的推移而发生的过渡,这并不是我想要的。
更新 1:
根据 Mihai Fratu 的回答,我能够解决我的问题。为了将来参考,我想添加一个最小的 Swift 4 代码示例:
// Create the layer with the circle path (UIBezierPath)
let circlePathLayer = CAShapeLayer()
circlePathLayer.path = UIBezierPath([...]).cgPath
circlePathLayer.strokeEnd = 0.0
circlePathLayer.strokeColor = UIColor.black.cgColor
circlePathLayer.fillColor = UIColor.clear.cgColor
self.layer.addSublayer(circlePathLayer)
// Create animation to animate the progress (circle slowly draws)
let progressAnimation = CABasicAnimation()
progressAnimation.keyPath = #keyPath(CAShapeLayer.strokeEnd)
progressAnimation.fromValue = 0.0
progressAnimation.toValue = 1
// Create animation to change the color
let colorAnimation = CABasicAnimation()
colorAnimation.keyPath = #keyPath(CAShapeLayer.strokeColor)
colorAnimation.fromValue = UIColor.black.cgColor
colorAnimation.toValue = UIColor.red.cgColor
colorAnimation.beginTime = 3.75 // Since your total animation is 10s long, 75% is 7.5s - play with this if you need something else
colorAnimation.duration = 0.001 // make this really small - this way you "hide" the transition
colorAnimation.fillMode = .forwards
// Group animations together
let progressAndColorAnimation = CAAnimationGroup()
progressAndColorAnimation.animations = [progressAnimation, colorAnimation]
progressAndColorAnimation.duration = 5
// Add animations to the layer
circlePathLayer.add(progressAndColorAnimation, forKey: "strokeEndAndColor")
【问题讨论】:
-
所以你想改变颜色,让圆的开始有一种颜色,而结束另一种颜色?
-
如果你想要的话,看看这个:stackoverflow.com/a/40190150/831838
-
@MihaiFratu 不,我应该解释得更好。整个圈子应该改成
strokeColor。我会检查你的链接。 -
但是你需要使用 CABasicAnimation。让我在下面给你写一个答案。
标签: swift core-animation cashapelayer