使用CABasicAnimation后,防止CAGradientLayer位置返回原始值

我正在尝试使渐变具有动画效果,以便两种颜色的位置从左向右移动。问题是,一旦动画完成,渐变位置就会回到原来的位置。使用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()

如何防止动画完成后的位置的复位?

回答:

你只需告诉它不是在完成删除和设置位置为新值:

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)

}

以上是 使用CABasicAnimation后,防止CAGradientLayer位置返回原始值 的全部内容, 来源链接: utcz.com/qa/267300.html

回到顶部