这是一个可以帮助某人的 Swift 示例
这是渐变层上的动画。它正在为属性设置动画.locations
。
@robMayoff 回答完全解释的关键点是:
令人惊讶的是,当你做一个图层动画时,你实际上设置了最终值,首先,在你开始动画之前!
下面是一个很好的例子,因为动画会无休止地重复。
当动画无休止地重复时,如果你犯了“在动画之前忘记设置值”的经典错误,你会偶尔看到动画之间的“闪光”!
var previousLocations: [NSNumber] = []
...
func flexTheColors() { // "flex" the color bands randomly
let oldValues = previousTargetLocations
let newValues = randomLocations()
previousTargetLocations = newValues
// IN FACT, ACTUALLY "SET THE VALUES, BEFORE ANIMATING!"
theLayer.locations = newValues
// AND NOW ANIMATE:
CATransaction.begin()
// and by the way, this is how you endlessly animate:
CATransaction.setCompletionBlock{ [weak self] in
if self == nil { return }
self?.animeFlexColorsEndless()
}
let a = CABasicAnimation(keyPath: "locations")
a.isCumulative = false
a.autoreverses = false
a.isRemovedOnCompletion = true
a.repeatCount = 0
a.fromValue = oldValues
a.toValue = newValues
a.duration = (2.0...4.0).random()
theLayer.add(a, forKey: nil)
CATransaction.commit()
}
以下内容可能有助于为新程序员澄清一些事情。请注意,在我的代码中,我这样做:
// IN FACT, ACTUALLY "SET THE VALUES, BEFORE ANIMATING!"
theLayer.locations = newValues
// AND NOW ANIMATE:
CATransaction.begin()
...set up the animation...
CATransaction.commit()
但是在另一个答案的代码示例中,它是这样的:
CATransaction.begin()
...set up the animation...
// IN FACT, ACTUALLY "SET THE VALUES, BEFORE ANIMATING!"
theLayer.locations = newValues
CATransaction.commit()
关于“在动画之前设置值!”的代码行的位置。..
让那行实际上“在” begin-commit 代码行中实际上是完全可以的。只要你在.commit()
.
我只提到这一点,因为它可能会使新动画师感到困惑。