0
我正在嘗試使漸變具有動畫效果,以便兩種顏色的位置從左向右移動。問題是,一旦動畫完成,漸變位置就會回到原來的位置。使用CABasicAnimation後,防止CAGradientLayer位置返回原始值
這裏是我的遊樂場代碼:
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()
如何防止動畫完成後的位置的復位?
個人而言,我喜歡最後的解決方案,因爲它有一個完成塊..但它是所有的偏好和需求。決定你自己最適合你.. – Brandon
我已經嘗試了第一個解決方案,但它不起作用。我會嘗試其他兩種解決方案。敬請期待... – DJSK
最後的解決方案是唯一可行的解決方案。我會繼續標記它是正確的。謝謝! – DJSK