【问题标题】:CoreAnimation — Layer flickers to final value before animation starts?CoreAnimation — 在动画开始之前图层闪烁到最终值?
【发布时间】:2019-04-06 22:17:36
【问题描述】:

我正在尝试对图层的背景颜色从红色到蓝色进行简单的 CABasicAnimation。

添加动画并设置模型层的最终值后,动画闪烁为蓝色,然后再次变为红色,并动画为蓝色。

我的代码是:

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    // Create red layer and add to view
    let redLayer = CALayer()
    redLayer.backgroundColor = UIColor.red.cgColor
    redLayer.position = view.center
    redLayer.bounds.size = CGSize(width: 100, height: 100)
    view.layer.addSublayer(redLayer)

    DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1)) {

        // After a 1 second delay, animate from red to blue.

        let anim = CABasicAnimation(keyPath: "backgroundColor")
        anim.duration = 3
        anim.fromValue = redLayer.backgroundColor
        anim.toValue = UIColor.blue.cgColor
        redLayer.add(anim, forKey: "")

        // Set background color to final value
        redLayer.backgroundColor = UIColor.blue.cgColor
    }
}

这里发生了什么?

【问题讨论】:

    标签: ios core-animation calayer cabasicanimation


    【解决方案1】:

    简短的回答是,当您更新图层的隐式动画属性时,您将获得一个隐式动画(在这种情况下为backgroundColor)。

    这个 0.25 秒的动画优先于您的显式动画,因为它是在之后添加的。之所以会出现这种隐式动画,是因为该层是“独立的”(即,它不属于视图)。

    要摆脱这种隐式动画,您可以创建 CATransaction 并仅对更新图层属性的范围禁用操作:

    CATransaction.begin()
    CATransaction.setDisableActions(true)
    
    redLayer.backgroundColor = UIColor.blue.cgColor
    
    CATransaction.commit()
    

    作为禁用隐式动画的替代方法,您还可以在添加显式动画之前更新图层。如果您想了解更多信息,我对在添加动画in this answer 之前或之后更新图层的含义有相当详细的解释。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-21
      • 1970-01-01
      • 2020-03-04
      • 1970-01-01
      • 2020-01-10
      • 1970-01-01
      • 2021-05-25
      • 1970-01-01
      相关资源
      最近更新 更多