我尝试制作渐变动画,以便两种颜色的位置从左向右移动。问题是,一旦动画完成,渐变位置会回弹到原始位置。
这是我的游乐场代码:
import UIKit
import PlaygroundSupport
class MyViewController : UIViewController {
let gradientLayer: CAGradientLayer = {
let layer = CAGradientLayer()
layer.colors = [ UIColor.red.cgColor, UIColor.blue.cgColor ]
layer.locations = [0.0, 0.5]
layer.startPoint = CGPoint(x: 0.0, y: 1.0)
layer.endPoint = CGPoint(x: 1.0, y: 1.0)
return layer
}()
override func viewDidLoad() {
super.viewDidLoad()
view.layer.addSublayer(gradientLayer)
gradientLayer.frame = view.bounds
let gradientChangeAnimation = CABasicAnimation(keyPath: "locations")
gradientChangeAnimation.duration = 1
gradientChangeAnimation.toValue = [0.5, 1.0]
gradientLayer.add(gradientChangeAnimation, forKey: nil)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
gradientLayer.frame = view.frame
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
如何在动画完成后阻止重置位置?
答案 0 :(得分:1)
您可以告诉它在完成时不删除并将位置设置为新值:
override func viewDidLoad() {
super.viewDidLoad()
view.layer.addSublayer(gradientLayer)
gradientLayer.frame = view.bounds
CATransaction.begin()
CATransaction. setCompletionBlock {
gradientLayer.locations = [0.5, 1.0]
gradientLayer.removeAllAnimations()
}
let gradientChangeAnimation = CABasicAnimation(keyPath: "locations")
gradientChangeAnimation.duration = 1
gradientChangeAnimation.toValue = [0.5, 1.0]
gradientLayer.add(gradientChangeAnimation, forKey: nil)
CATransaction.commit()
}
或适当设置 fillMode 和 isRemovedOnCompletion 属性。
override func viewDidLoad() {
super.viewDidLoad()
view.layer.addSublayer(gradientLayer)
gradientLayer.frame = view.bounds
let gradientChangeAnimation = CABasicAnimation(keyPath: "locations")
gradientChangeAnimation.duration = 1
gradientChangeAnimation.toValue = [0.5, 1.0]
gradientChangeAnimation.fillMode = kCAFillModeForwards
gradientChangeAnimation.isRemovedOnCompletion = false
gradientLayer.add(gradientChangeAnimation, forKey: nil)
}