我想在我的应用程序中包含一个动画渐变,并且我当前正在使用CATransition来完成任务。但是,动画在iOS和macOS上都有很高的能耗(我开发了这两个应用程序)。有谁知道如何解决这个问题?是否有一个性能更好的库,或者我可以使用其他动画?
我当前拥有的代码如下:
var gradient = CAGradientLayer()
var color = 0
var animationGradient = [CGColor(red: 0.94, green: 0.32, blue: 0.31, alpha: 1.00),
CGColor(red: 0.93, green: 0.25, blue: 0.48, alpha: 1.00),
CGColor(red: 0.67, green: 0.28, blue: 0.74, alpha: 1.00),
CGColor(red: 0.50, green: 0.34, blue: 0.76, alpha: 1.00),
CGColor(red: 0.48, green: 0.53, blue: 0.80, alpha: 1.00),
CGColor(red: 0.26, green: 0.65, blue: 0.96, alpha: 1.00),
CGColor(red: 0.16, green: 0.71, blue: 0.96, alpha: 1.00),
CGColor(red: 0.15, green: 0.78, blue: 0.85, alpha: 1.00),
CGColor(red: 0.15, green: 0.65, blue: 0.61, alpha: 1.00),
CGColor(red: 0.40, green: 0.73, blue: 0.41, alpha: 1.00),
CGColor(red: 0.61, green: 0.80, blue: 0.40, alpha: 1.00),
CGColor(red: 0.83, green: 0.88, blue: 0.34, alpha: 1.00),
CGColor(red: 1.00, green: 0.93, blue: 0.35, alpha: 1.00),
CGColor(red: 1.00, green: 0.79, blue: 0.16, alpha: 1.00),
CGColor(red: 1.00, green: 0.65, blue: 0.15, alpha: 1.00),
CGColor(red: 1.00, green: 0.44, blue: 0.26, alpha: 1.00)]
var animationIndex = 0
var fromColors: [CGColor] = []
var toColors: [CGColor] = []
func createGradient() {
fromColors = [CGColor(red: 1.00, green: 1.00, blue: 1.00, alpha: 1.00),
CGColor(red: 1.00, green: 1.00, blue: 1.00, alpha: 1.00)]
toColors = [CGColor(red: 0.67, green: 0.28, blue: 0.74, alpha: 1.00),
CGColor(red: 0.16, green: 0.71, blue: 0.96, alpha: 1.00)]
gradient.colors = fromColors
gradient.startPoint = CGPoint(x: 0.0, y: 1.0)
gradient.endPoint = CGPoint(x: 1.0, y: 0.0)
gradient.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.size.width, height: self.view.frame.size.height)
self.view.layer?.insertSublayer(gradient, at: 100)
animateLayer(withDuration: 0.5)
}
func animateLayer(withDuration duration: Double){
var animation = CATransition()
animation.duration = duration
animation.isRemovedOnCompletion = true
animation.fillMode = .forwards
animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
animation.delegate = self as? CAAnimationDelegate
animation.type = .fade
self.gradient.add(animation, forKey:"animateGradient")
gradient.colors = toColors
}
func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
self.fromColors = toColors
color = (color + Int.random(in: 2...6)) % animationGradient.count
toColors = [fromColors[1],
animationGradient[color]]
animateLayer(withDuration: 6.00)
}
代码可以正常工作,动画也可以工作,但是性能却很糟糕。有谁有更好的解决方案?我对任何提示都很满意!