2017-12-27 430 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

相關問題