当用户点击按钮时,我需要为圈子的进展设置动画。我当前正在使用CAShapeLayer
和CABasicAnimation
。像这样的代码:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var circleContainerView: UIView!
var progressPts = [0.1, 0.3, 0.7, 0.5]
let circleLayer = CAShapeLayer()
override func viewDidLoad() {
super.viewDidLoad()
setupCircle()
}
@IBAction func didTapAnimate(_ sender: Any) {
guard let pt = progressPts.first else { return }
let animateStroke = CABasicAnimation(keyPath: "strokeEnd")
animateStroke.toValue = pt
animateStroke.duration = 2.0
animateStroke.fillMode = .forwards
animateStroke.isRemovedOnCompletion = false
circleLayer.add(animateStroke, forKey: "MyAnimation")
progressPts.removeFirst()
}
private func setupCircle() {
circleLayer.frame = CGRect(origin: .zero, size: circleContainerView.bounds.size)
let center = CGPoint(x: circleLayer.bounds.width / 2.0,
y: circleLayer.bounds.height / 2.0)
circleLayer.path = UIBezierPath(arcCenter: center,
radius: (circleLayer.bounds.height / 2.0) - 5.0,
startAngle: 0,
endAngle: 2 * CGFloat.pi, clockwise: true).cgPath
circleLayer.fillColor = UIColor.clear.cgColor
circleLayer.lineWidth = 10.0
circleLayer.strokeColor = UIColor.red.cgColor
circleLayer.strokeEnd = 0.0
circleContainerView.layer.addSublayer(circleLayer)
}
}
为使笔画在动画结束时停留在正确的位置,我还需要将fillMode
和.forwards
设置为isRemovedOnCompletion
。这对于第一个动画效果很好。但是,在下一个动画中,笔划会首先重置:
我在这里做错了什么?如何为每个新的进度位置设置动画而不重置?另外,将false
设置为isRemovedOnCompletion
肯定不是一个好主意,因为该图层最终会附加多个动画。
答案 0 :(得分:2)
我只是使用from值属性来完成整个圆而无需重置,仅使用以下代码即可平滑地制作动画
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var circleContainerView: UIView!
var progressPts = [0.1, 0.3, 0.7, 0.5]
var previousPts = 0.0
let circleLayer = CAShapeLayer()
var animateStroke: CABasicAnimation!
override func viewDidLoad() {
super.viewDidLoad()
setupCircle()
}
@IBAction func didTapAnimate(_ sender: Any) {
guard let pt = progressPts.first else { return }
animateStroke.fromValue = previousPts
animateStroke.toValue = pt
animateStroke.duration = 2.0
animateStroke.fillMode = .forwards
animateStroke.isRemovedOnCompletion = false
circleLayer.add(animateStroke, forKey: "MyAnimation")
previousPts = progressPts.removeFirst()
}
private func setupCircle() {
animateStroke = CABasicAnimation(keyPath: "strokeEnd")
circleLayer.frame = CGRect(origin: .zero, size: circleContainerView.bounds.size)
let center = CGPoint(x: circleLayer.bounds.width / 2.0,
y: circleLayer.bounds.height / 2.0)
circleLayer.path = UIBezierPath(arcCenter: center,
radius: (circleLayer.bounds.height / 2.0) - 5.0,
startAngle: 0,
endAngle: 2 * CGFloat.pi, clockwise: true).cgPath
circleLayer.fillColor = UIColor.clear.cgColor
circleLayer.lineWidth = 10.0
circleLayer.strokeColor = UIColor.red.cgColor
circleLayer.strokeEnd = 0.0
circleContainerView.layer.addSublayer(circleLayer)
}
}
输出