廢話不說先上圖
有人開始說了 ,你這等于脫褲子放屁,那我引入大佬的一句話,存在即為合理,下面是GitHub Lottie提出的issues
4DA653747AE599E5EFFAAF2F00120FFB.jpg
CPU占用過高,這不能忍啊,我是這個小動畫是一個按鈕上的,當直播狀態(tài)為直播中時間展示,就僅僅一個這么小的動畫 CPU占用在30%左右,官方作者也提出了對應的性能問題
A9A8DBCCA1B856E99485774B2B04F21C.jpg
英語不好的我,直接翻譯
E9A5CC87-AE8C-4824-A8D0-6AF8BDCEF5B6.png
大致的意思就是swift的鍋,這種高深問題,不是我能搞定的,于是想著用原生寫,看著也挺簡單,實現(xiàn)起來也是有點波折的,我還惡補了layer有關的東西
廢話不說上代碼
import UIKit
class SDPlayAnimationView: UIView {
/// 是否添加了動畫
private var isPlayAnimation:Bool {
get{
let animation = lineOneLayer.animation(forKey: "animation1")
guard let _ = animation else {
return false
}
return true
}
}
override func layoutSubviews() {
super.layoutSubviews()
layoutSubUI()
}
deinit {
stopAnimation()
}
private func layoutSubUI() {
let animationWidth = self.bounds.size.width
let animationHeight = self.bounds.size.height
let itemWidth = animationWidth / 3 * 0.45
lineOneLayer.frame = CGRect(x: 0, y: animationHeight - 10, width: itemWidth, height: 10)
lineTwoLayer.frame = CGRect(x: animationWidth / 2 - itemWidth / 2, y: self.frame.size.height - 20, width: itemWidth, height: 20)
lineThreeLayer.frame = CGRect(x: animationWidth - itemWidth , y: self.frame.size.height - 15 , width: itemWidth, height: 15)
self.layer.sublayers?.forEach({ (item) in
item.cornerRadius = itemWidth * 0.5
})
}
private lazy var lineOneLayer:CALayer = setupAnimationLayer()
private lazy var lineTwoLayer:CALayer = setupAnimationLayer()
private lazy var lineThreeLayer:CALayer = setupAnimationLayer()
}
extension SDPlayAnimationView: CAAnimationDelegate{
/// 快速創(chuàng)建SDPlayAnimationView
/// - Returns: SDPlayAnimationView
public class func playAnimationView() -> SDPlayAnimationView {
return SDPlayAnimationView()
}
/// 停止動畫
public func stopAnimation() {
self.layer.sublayers?.forEach({ (item) in
item.removeAllAnimations()
})
}
/// 開始動畫
public func startAnimation() {
if isPlayAnimation {
return
}
self.layoutIfNeeded()
let height = self.bounds.size.height
setupKeyframeAnimation(layer: lineOneLayer, values: [height * 0.2,height * 0.6,height,height * 0.6,height * 0.2],key: "animation1")
setupKeyframeAnimation(layer: lineTwoLayer, values: [height * 0.6,height,height * 0.6,height * 0.2,height * 0.6],key: "animation2")
self.setupKeyframeAnimation(layer: self.lineThreeLayer, values: [height,height * 0.6,height * 0.2,height * 0.6,height],key: "animation3")
}
private func setupAnimationLayer() -> CALayer {
let layer = CALayer()
layer.backgroundColor = UIColor.white.cgColor
layer.anchorPoint = CGPoint(x: 0, y: 1)
self.layer.addSublayer(layer)
return layer
}
private func setupKeyframeAnimation(layer:CALayer,values:[Any] ,key:String) {
let animation = CAKeyframeAnimation(keyPath:"bounds.size.height")
animation.values = values
animation.duration = 1
animation.repeatCount = MAXFLOAT
animation.isRemovedOnCompletion = false
layer.add(animation, forKey: key)
}
}
再看下CPU,微絲不動,美滋滋
69105AE878C6309D9783D86A69DCBE4F.jpg
最后上傳下代碼地址,可以做對比
https://github.com/lanyuzx/CustomPlayAnimation/tree/master