在设置AVVideoComposition时,需要为AVVideoCompositionCoreAnimationTool设置delegate,并实现其中的“animationTool:didAnimateProperty:ofLayer:atTime:withValue:”方法。在该方法内,判断自定义属性的键是否符合动画处理,如果是则对其进行相应的动画处理。
示例代码:
// 自定义属性的键
let customAnimationKey = "customAnimationKey"
// 设置AVAssetExportSession
let exporter = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetHighestQuality)
exporter.outputFileType = .mp4
exporter.videoComposition = videoComposition
// 设置AVVideoCompositionCoreAnimationTool
let animationTool = AVVideoCompositionCoreAnimationTool(postProcessingAsVideoLayer: videoLayer, in: videoComposition)
animationTool.delegate = self // 设置delegate
videoComposition.animationTool = animationTool
// 实现AVVideoCompositionCoreAnimationToolDelegate中的方法,进行动画处理
extension ViewController: AVVideoCompositionCoreAnimationToolDelegate {
func animationTool(_ animationTool: AVVideoCompositionCoreAnimationTool, didAnimateProperty prop: String, ofLayer layer: CALayer, atTime time: CMTime, withValue value: Any) {
if prop == customAnimationKey {
// 对自定义属性进行动画处理
let anim = CABasicAnimation(keyPath: "opacity")
anim.fromValue = 0
anim.toValue = 1
anim.duration = 1
layer.opacity = 1
layer.add(anim, forKey: "opacity")
}
}
}