開發中常常須要加載數據,這時候就須要一個加載動畫,最近寫了2個加載動畫,但願對你們有所幫助。文章末尾有提供OC和Swift雙語的CLDemo下載,代碼比較簡單,就不詳細解析了,Demo中已經進行封裝,能夠直接使用,這裏貼出核心代碼。git
核心代碼github
private func initLayer() -> Void {
let origin_x: CGFloat = frame.size.width * 0.5
let origin_y: CGFloat = frame.size.height * 0.5
for item in 0 ..< defaultConfigure.number {
//建立layer
let scale: CGFloat = CGFloat(defaultConfigure.number + 1 - item) / CGFloat(defaultConfigure.number + 1)
let layer: CALayer = CALayer()
layer.backgroundColor = defaultConfigure.backgroundColor.cgColor
layer.frame = CGRect.init(x: -5000, y: -5000, width: scale * defaultConfigure.diameter, height: scale * defaultConfigure.diameter)
layer.cornerRadius = scale * defaultConfigure.diameter * 0.5;
//運動路徑
let pathAnimation: CAKeyframeAnimation = CAKeyframeAnimation.init(keyPath: "position")
pathAnimation.calculationMode = .paced;
pathAnimation.fillMode = .forwards;
pathAnimation.isRemovedOnCompletion = false;
pathAnimation.duration = (defaultConfigure.duration) - Double((defaultConfigure.intervalDuration) * Double(defaultConfigure.number));
pathAnimation.beginTime = Double(item) * defaultConfigure.intervalDuration;
pathAnimation.timingFunction = CAMediaTimingFunction.init(name: .easeInEaseOut)
pathAnimation.path = UIBezierPath(arcCenter: CGPoint.init(x: origin_x, y: origin_y), radius: (self.frame.size.width - self.defaultConfigure.diameter) * 0.5, startAngle: defaultConfigure.startAngle, endAngle: defaultConfigure.endAngle, clockwise: true).cgPath
//動畫組,動畫組時間長於單個動畫時間,會有停留效果
let group: CAAnimationGroup = CAAnimationGroup()
group.animations = [pathAnimation]
group.duration = defaultConfigure.duration
group.isRemovedOnCompletion = false
group.fillMode = .forwards
group.repeatCount = MAXFLOAT
layer.add(group, forKey: "RotateAnimation")
layerArray.append(layer)
}
}
複製代碼
核心代碼bash
override init(frame: CGRect) {
super.init(frame: frame)
width = frame.size.width
height = frame.size.height
layer.backgroundColor = configure.outBackgroundColor.cgColor
layer.mask = shapeLayer(lineWidth: configure.outLineWidth, start: 0, end: 1)
animationLayer.frame = layer.bounds
animationLayer.backgroundColor = configure.inBackgroundColor.cgColor
animationLayer.mask = shapeLayer(lineWidth: configure.inLineWidth, start: configure.strokeStart, end: configure.strokeEnd)
layer.addSublayer(animationLayer)
rotationAnimation.fromValue = 0
rotationAnimation.toValue = Double.pi * 2
rotationAnimation.repeatCount = MAXFLOAT
rotationAnimation.duration = configure.duration
rotationAnimation.isRemovedOnCompletion = false
rotationAnimation.fillMode = .forwards
rotationAnimation.timingFunction = CAMediaTimingFunction(name: .linear)
}
複製代碼
核心代碼已經貼出,完整代碼請查看Demo,爲了方便你們學習,這裏提供了OC和Swift兩種語言分別實現的----->>>CLDemo,若是對你有所幫助,歡迎Star。app