我想慢慢为三色渐变设置动画。
我有这样的自定义UIView
:
class MyView: UIView, CAAnimationDelegate {
lazy var gradientLayer: CAGradientLayer = {
let l = CAGradientLayer()
l.frame = self.frame
l.colors = self.colors
l.startPoint = CGPoint(x: 0, y: 0)
l.endPoint = CGPoint(x: 1, y: 0)
l.mask = self.textLayer
return l
}()
lazy var textLayer: CATextLayer = {
let l = CATextLayer()
l.frame = self.frame
l.string = "test".uppercased()
l.fontSize = 23
return l
}()
var colors: [CGColor] = [
UIColor.red.cgColor,
UIColor.purple.cgColor,
UIColor.blue.cgColor
]
init() {
...
self.layer.addSublayer(gradientLayer)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func animate() {
var newColors = colors
let lastColor: CGColor = newColors.last!
newColors.removeLast()
newColors.insert(lastColor, at: 0)
colors: newColors
gradientLayer.colors = newColors
let a = CABasicAnimation(keyPath:"colors")
a.toValue = newColors
a.duration = 0.1
a.isRemovedOnCompletion = true
a.fillMode = kCAFillModeForwards
a.delegate = self
gradientLayer.add(a, forKey:"animateGradient")
}
func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
animate()
}
}
这很有效,但速度非常快。如何减慢动画速度,不会让它变得僵硬?
我是否必须在colors
数组中添加几百种颜色,以便它能够循环播放?
由于
答案 0 :(得分:0)
除非我在代码中遗漏了某些东西,否则你没有在动画中设置fromValue。当然,在将颜色切换为newColors之前,您需要将其设置为先前的颜色值:
func animate() {
let oldColors = colors
var newColors = colors
let lastColor: CGColor = newColors.last!
newColors.removeLast()
newColors.insert(lastColor, at: 0)
colors = newColors
gradientLayer.colors = newColors
let a = CABasicAnimation(keyPath:"colors")
// New line here ->
a.fromValue = oldColors
a.toValue = newColors
a.duration = 0.1
a.isRemovedOnCompletion = true
a.fillMode = kCAFillModeForwards
a.delegate = self
gradientLayer.add(a, forKey:"animateGradient")
}
这就是你没有真正获得动画的原因 - 你的代码被有效地设置以创建延迟的快照过渡。