動畫為三個點不停的跑到下一個地點。
LoadingView 會是一個正方形,在這個正方形裡面定義三個點的位置。
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)
}
動畫看起來是球在三個點之間不停的移動,時間上我們只要讓一個點重複從原來的位置移動到下一個位置,視覺上的效果就達成了。
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")
}
}