繼續通過練習來提高做動畫的能力。
動畫的三個點,線條拉伸、線條回收、每次的出發點不同。
建立 LoadingView 放上 cycleLayer 設定填充色、筆頭、線條等。
fileprivate let cycleLayer: CAShapeLayer = CAShapeLayer()
fileprivate func setupView() {
cycleLayer.lineWidth = 4
cycleLayer.fillColor = UIColor.clear.cgColor
cycleLayer.strokeColor = UIColor.white.cgColor
cycleLayer.lineCap = kCALineCapRound
cycleLayer.lineJoin = kCALineJoinRound
cycleLayer.frame = bounds
cycleLayer.path = UIBezierPath(ovalIn: bounds).cgPath
layer.addSublayer(cycleLayer)
}
let strokeStartAnimation = CABasicAnimation(keyPath: "strokeStart")
strokeStartAnimation.fromValue = -1
strokeStartAnimation.toValue = 1.0
strokeStartAnimation.repeatCount = Float.infinity
cycleLayer.add(strokeStartAnimation, forKey: "strokeStartAnimation")
let strokeEndAnimation = CABasicAnimation(keyPath: "strokeEnd")
strokeEndAnimation.fromValue = 0
strokeEndAnimation.toValue = 1.0
strokeEndAnimation.repeatCount = Float.infinity
cycleLayer.add(strokeEndAnimation, forKey: "strokeStartAnimation")
通過 CAAnimationGroup 我們可以把上面兩個動畫結合起來。
let animationGroup = CAAnimationGroup()
animationGroup.repeatCount = Float.infinity
animationGroup.animations = [strokeStartAnimation, strokeEndAnimation]
animationGroup.duration = 3.0
cycleLayer.add(animationGroup, forKey: "animationGroup")
每一次開始做動畫的位置不同,可以通過將整個圓圈進行旋轉來讓視覺上看起來每次線條的出發點不同。
let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotateAnimation.fromValue = 0
rotateAnimation.toValue = Double.pi * 2
rotateAnimation.repeatCount = Float.infinity
rotateAnimation.duration = 3.0 * 4
cycleLayer.add(rotateAnimation, forKey: "rotateAnimation")