2017-12-27 453 views
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() 

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

回答

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() 
} 

或设置适当的在fillModeisRemovedOnCompletion性能。

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) 
} 
+1

个人而言,我喜欢最后的解决方案,因为它有一个完成块..但它是所有的偏好和需求。决定你自己最适合你.. – Brandon

+0

我已经尝试了第一个解决方案,但它不起作用。我会尝试其他两种解决方案。敬请期待... – DJSK

+0

最后的解决方案是唯一可行的解​​决方案。我会继续标记它是正确的。谢谢! – DJSK

相关问题