ios - 使用动画生成插值

标签 ios core-animation uikit-dynamics

我想(滥用)使用 Core Animation 甚至 UIDynamics 来生成我可以用来控制其他参数的动画值( float )。

例如有一个缓入的动画,我想用一个“缓动”值来控制颜色。

最佳答案

核心动画当然可以为您做到这一点。您需要创建一个 CALayer 子类,其中包含您想要设置动画的新属性:

class CustomLayer: CALayer {

    @NSManaged var colorPercentage: Float

    override required init(layer: AnyObject) {
        super.init(layer: layer)

        if let layer = layer as? CustomLayer {
            colorPercentage = layer.colorPercentage
        } else {
            colorPercentage = 0.0
        }
    }

    required init?(coder decoder: NSCoder) {
        super.init(coder: decoder)
    }

    override class func needsDisplay(forKey key: String) -> Bool {
        var needsDisplay = super.needsDisplay(forKey: key)

        if key == "colorPercentage" {
            needsDisplay = true
        }

        return needsDisplay
    }

    override func action(forKey key: String) -> CAAction? {
        var action = super.action(forKey: key)

        if key == "colorPercentage" {
            action = super.action(forKey: "opacity")     // Create reference action from an existing CALayer key

            if let action = action as? CABasicAnimation {
                action.keyPath = key
                action.fromValue = value(forKeyPath: key)
            }
        }

        return action
    }

    override func display() {
        guard let presentationLayer = presentation() else { return }

        print("Current 'colorPercentage' value: \(presentationLayer.colorPercentage)")
        // Called for every frame of an animation involving "colorPercentage"
    }
}

(在 Swift 中,@NSManaged 是当前 Core Animation 将 colorPercentage 视为 Objective-C @dynamic 属性所必需的一种技巧。 )

按照此模式,您可以创建一个包含您自己的动画属性的自定义层。 display() 将在主线程上为动画的每一帧调用,因此您可以随时间响应值的变化,但您愿意:

let animation = CABasicAnimation(keyPath: "colorPercentage")
animation.duration = 1.0
animation.fromValue = customLayer.colorPercentage

customLayer.colorPercentage = 1.0
customLayer.add(animation, forKey: "colorPercentageAnimation")

作为奖励,action(forKey:) 可用于从 Core Animation 了解的“引用动画”创建 Action ,并将其配置为与您的自定义属性一起使用。这样,就可以在 UIKit 风格的动画闭包中调用 CALayer 动画,使用起来更加方便:

UIView.animate(withDuration: 1.0, animations: {
    customLayer.colorPercentage = 1.0            
})

关于ios - 使用动画生成插值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38854968/

相关文章:

ios - 我可以让 Realm Results 类使用协议(protocol)作为泛型吗?

ios - 在通知中心检查应用程序的禁用设置的内容是什么?

ios - 具有动画路径内容的 CALayer,使可检查/可设计

objective-c - 我如何最好地使用 UICollisionBehavior 来检测 View 何时不再显示在屏幕上?

ios - 了解 UIDynamics 如何计算位置

ios - UIKit 动态 : recognize rounded Shapes and Boundaries

ios - 在 iOS 的表格 View 单元格中更改披露指示器附件 View 的颜色/ View 的最佳方法是什么?

ios - 有没有办法将一个ios设备的屏幕共享给另一台设备

iphone - CoreGraphics 和 CoreAnimation 有什么不同?

iphone - 手动淡入新添加的 subview ?