LoadingAnimation
動畫為三個點不停的跑到下一個地點。
LoadingView
LoadingView 會是一個正方形,在這個正方形裡面定義三個點的位置。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
fileprivate let dotCount = 3 fileprivate var dotGroup:[CAShapeLayer] = [] fileprivate var animationDuration = 0.8 fileprivate var lineWidth:CGFloat = 8.0 fileprivate var width: CGFloat { return frame.size.width / 2 } fileprivate var leftPoint:CGPoint { return CGPoint(x: 0, y: width) } fileprivate var rightPoint:CGPoint { return CGPoint(x: width, y: width) } fileprivate var topPoint: CGPoint { return CGPoint(x: width/2, y: 0) } |
動畫原理
動畫看起來是球在三個點之間不停的移動,時間上我們只要讓一個點重複從原來的位置移動到下一個位置,視覺上的效果就達成了。
- points – 所以初始化的位置
- nextPoints – 下一個位置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
fileprivate func setupView() { points = [rightPoint, leftPoint, topPoint] nextPoints = [leftPoint, topPoint, rightPoint] for i in 0 ..< dotCount { let dotLayer = CAShapeLayer() dotLayer.bounds = CGRect(x: 0, y: 0, width: lineWidth, height: lineWidth) dotLayer.path = UIBezierPath(ovalIn: dotLayer.bounds).cgPath dotLayer.fillColor = UIColor.white.cgColor dotLayer.strokeColor = UIColor.white.cgColor dotLayer.position = points[i] layer.addSublayer(dotLayer) dotGroup.append(dotLayer) } } func startLoading() { for i in 0 ..< dotCount { let dotLayer = dotGroup[i] let positionAnimation = CABasicAnimation(keyPath: "position") positionAnimation.toValue = nextPoints[i] positionAnimation.duration = animationDuration positionAnimation.repeatCount = Float.infinity dotLayer.add(positionAnimation, forKey: "positionAnimation") } } |
Reference
- 在 Github 上有本文相關的 Source Code