今天要來教大家做一個簡單的 loading 動畫
會使用到一些更進階的 CABasicAnimation 的用法
首先我們要先用 CAShapeLayer 畫一個空心圓
let circleCenter = CGPoint(x: 175, y: 350)
let circleLayer = CAShapeLayer()
let circlePath = UIBezierPath(arcCenter: circleCenter, radius: 50, startAngle: 0 - (CGFloat.pi / 2), endAngle: (CGFloat.pi * 2) - (CGFloat.pi / 2), clockwise: true)
circleLayer.path = circlePath.cgPath
circleLayer.strokeColor = UIColor.blue.cgColor
circleLayer.fillColor = UIColor.clear.cgColor
circleLayer.lineWidth = 3
再來我們要使用的是 CAKeyframeAnimation,可以把它當作一個比較進階的 CABasicAimation
有兩個屬性要介紹一下
values 要放一個值的陣列(範圍是 0~1)
keyTimes 要放一個時間的陣列(範圍是 0~1) 值是根據 CAAnimation 的 duration * 值
values 與 keyTimes 是一個對一個的,所以有幾個 values 值就有幾個 keyTimes 值
實際的作法如下
let circleAnimation1 = CABasicAnimation(keyPath: "strokeStart")
circleAnimation1.values = [0.0, 0.0, 0.8, 1]
circleAnimation1.keyTimes = [0.0, 0.1, 0.9, 1.0]
let circleAnimation2 = CAKeyframeAnimation(keyPath: "strokeEnd")
circleAnimation2.values = [0.0, 0.1, 0.9, 1]
circleAnimation2.keyTimes = [0.0, 0.1, 0.9, 1.0]
再來要介紹 CAAnimationGroup ,它可以將多個 CAAnimation 合再一起,不用再一個一個加入進 layer
其中有幾個新的屬性要介紹一下
repeatCount 是指動畫要重複的次數
如果要讓動畫無限重播的話,我們可以使用 Float.infinity
timingFunction 是速度控制函数
其中有四個屬性可以選如下:
kCAMediaTimingFunctionLinear:線性
kCAMediaTimingFunctionEaseIn:漸進
kCAMediaTimingFunctionEaseOut:漸岀
kCAMediaTimingFunctionEaseInEaseOut:漸進漸出
let circleAnimationGroup = CAAnimationGroup()
circleAnimationGroup.animations = [circleAnimation1, circleAnimation2]
circleAnimationGroup.duration = 3
circleAnimationGroup.repeatCount = Float.infinity
let timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
circleAnimationGroup.timingFunction = timingFunction
circleLayer.add(circleAnimationGroup, forKey: "loadingAnimation")
self.view.layer.addSublayer(circleLayer)
效果如下