我想(滥用)使用 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/