我尝试通过AVExportSession为我的自定义CALayer导出动画,请找到以下设置:
class CustomAnimatable: CALayer
{
@NSManaged var brightness: CGFloat
override init(layer: Any) {
super.init(layer: layer);
if let l = layer as? CustomAnimatable {
self.brightness = l.brightness;
}
}
override func action(forKey event: String) -> CAAction?
{
if event == "brightness" {
let animation = CABasicAnimation(keyPath: event);
animation.fromValue = presentation()?.brightness ?? self.brightness;
return animation;
}
return super.action(forKey: event);
}
override class func needsDisplay(forKey key: String) -> Bool
{
if key == "brightness" {
return true;
}
return super.needsDisplay(forKey: key);
}
override func display()
{
print("\(self) \(presentation()?.brightness) \(self.brightness)")
}
}
这是预先设置的导出会话:
func render()
{
......
let parentLayer = CALayer();
let videoLayer = CALayer();
let animationLayer = CustomAnimatable()
parentLayer.frame = frame;
videoLayer.frame = frame;
animationLayer.frame = frame;
parentLayer.addSublayer(videoLayer);
parentLayer.addSublayer(animationLayer);
CATransaction.begin()
CATransaction.setAnimationDuration(2.2);
CATransaction.setDisableActions(true);
CATransaction.setAnimationTimingFunction(CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear))
let anim = CABasicAnimation(keyPath: "brightness");
anim.fromValue = 1.0;
anim.fillMode = kCAFillModeBoth;
anim.beginTime = AVCoreAnimationBeginTimeAtZero;
anim.repeatCount = 1;
anim.toValue = 0.0;
anim.isRemovedOnCompletion = false;
animationLayer.add(anim, forKey: "anim")
CATransaction.commit()
let videoComposition = AVMutableVideoComposition();
videoComposition.renderSize = CGSize(width: width, height: height);
videoComposition.instructions = [mainInstruction];
videoComposition.frameDuration = CMTimeMake(1, 30);
videoComposition.animationTool = AVVideoCompositionCoreAnimationTool(postProcessingAsVideoLayer: videoLayer, in: parentLayer);
....
}
问题是生成的视频中的brightness
值从1变为0而没有动画。如果我尝试为CALayer
的原生属性设置动画,例如opacity
- 导出的动画视频非常精细,不透明度从1平滑变为0。
我是否为自定义属性做错了?
我考虑过的事情:
CATransaction
以禁用隐式操作AVCoreAnimationBeginTimeAtZero
和isRemovedOnCompletion
为false session(Core Animation Gotchas部分)我对本机CALayer属性动画很好的事实感到有点困惑,因此导出会话设置似乎是正确的。
除此之外,如果我将自定义图层添加到视图并为brightness
属性设置动画 - 它也可以生动。所以这个问题似乎特定于使用AVExportSession渲染自定义属性动画。
答案 0 :(得分:0)
我不完全确定您在videoLayer
中添加了animationLayer
和parentLayer?
课程的原因。
parentLayer.addSublayer(videoLayer);
parentLayer.addSublayer(animationLayer);
使用以下代码希望对您有所帮助!
parentLayer.addSublayer(videoLayer);
videoLayer.addSublayer(animationLayer);