簡體   English   中英

使用 UIViewPropertyAnimator 同步動畫 CALayer 屬性和 UIView

[英]Synchronously animate CALayer property and UIView with UIViewPropertyAnimator

我正在使用UIViewPropertyAnimator為視圖的 position 設置動畫。 但是,我還想為 CALayer 屬性(如borderColor )制作動畫。 目前,它沒有動畫並在開始時立即更改,如下所示:

正方形向右移動的 GIF,邊框立即改變顏色

這是我的代碼:

class ViewController: UIViewController {
    var animator: UIViewPropertyAnimator?
    let squareView = UIView(frame: CGRect(x: 0, y: 40, width: 80, height: 80))
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.addSubview(squareView)
        
        squareView.backgroundColor = UIColor.blue
        squareView.layer.borderColor = UIColor.green.cgColor
        squareView.layer.borderWidth = 6
        
        animator = UIViewPropertyAnimator(duration: 2, curve: .easeOut, animations: {
            self.squareView.frame.origin.x = 100
            self.squareView.layer.borderColor = UIColor.red.cgColor
        })
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
            self.animator?.startAnimation()
        }
    }
}

我看了這個問題, How to synchronously animate a UIView and a CALayer ,答案建議使用“一個明確的 animation,就像一個基本的 animation”。 它說,

如果時間 function 和兩個動畫的持續時間相同,那么它們應該保持對齊。

但是,如果我使用CABasicAnimation ,我將失去UIViewPropertyAnimator的所有好處,比如在中間計時和停止。 我還需要跟蹤兩者。 有沒有辦法用UIViewPropertyAnimatorCALayer屬性設置動畫?

CABasicAnimation 有時間和關鍵幀 animation 停在中間。 但是,要復制上面的 animation:

squareView.layer.transform = CATransform3DMakeTranslation(100, 0, 0)
let fromValue = squareView.transform
let toValue = 100
let translateAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.transform))
translateAnimation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
translateAnimation.fromValue = fromValue
translateAnimation.toValue = toValue
translateAnimation.valueFunction = CAValueFunction(name: .translateX)

let fromColor = squareView.layer.borderColor
let toColor = UIColor.red.cgColor
let borderColorAnimation = CABasicAnimation(keyPath: "borderColor")
borderColorAnimation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
borderColorAnimation.fromValue = fromColor
borderColorAnimation.toValue = toColor

let groupAnimation = CAAnimationGroup()
groupAnimation.animations = [translateAnimation, borderColorAnimation]
groupAnimation.duration = 5
squareView.layer.add(groupAnimation, forKey: nil)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM