繼續通過練習來提高做動畫的能力。
Loading Animation – 模仿知乎 Loading 畫面
在 iOS 版的「知乎」應用裡面,讀取畫面的時候會跳出類似上面的載入動畫。
線條在圓形的邊上繞圈,每次的出發點都不一樣,並且線條在拉伸出去以後接著就跟著回收線條的動畫。
LoadingView
建立 LoadingView 放上 cycleLayer 設定填充色、筆頭、線條等。
1 |
fileprivate let cycleLayer: CAShapeLayer = CAShapeLayer() |
1 2 3 4 5 6 7 8 9 10 11 12 13 |
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) } |
動畫分解
動畫的三個點,線條拉伸、線條回收、每次的出發點不同。
通過 CABasicAnimation 對 strokeStart / strokeEnd 做動畫來實現畫面上的線條動畫。
線條回收
1 2 3 4 5 |
let strokeStartAnimation = CABasicAnimation(keyPath: "strokeStart") strokeStartAnimation.fromValue = -1 strokeStartAnimation.toValue = 1.0 strokeStartAnimation.repeatCount = Float.infinity cycleLayer.add(strokeStartAnimation, forKey: "strokeStartAnimation") |
線條拉伸
1 2 3 4 5 |
let strokeEndAnimation = CABasicAnimation(keyPath: "strokeEnd") strokeEndAnimation.fromValue = 0 strokeEndAnimation.toValue = 1.0 strokeEndAnimation.repeatCount = Float.infinity cycleLayer.add(strokeEndAnimation, forKey: "strokeStartAnimation") |
線條回收 + 線條拉伸
通過 CAAnimationGroup 我們可以把上面兩個動畫結合起來。
1 2 3 4 5 |
let animationGroup = CAAnimationGroup() animationGroup.repeatCount = Float.infinity animationGroup.animations = [strokeStartAnimation, strokeEndAnimation] animationGroup.duration = 3.0 cycleLayer.add(animationGroup, forKey: "animationGroup") |
線條回收 + 線條拉伸 + 繞圈
每一次開始做動畫的位置不同,可以通過將整個圓圈進行旋轉來讓視覺上看起來每次線條的出發點不同。
1 2 3 4 5 6 |
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") |
Reference
- 可以到 Gtihub 上看本文相關的 Source Code