ios 向AVMutableVideoComposition添加多个文本

q9rjltbz  于 2023-06-25  发布在  iOS
关注(0)|答案(2)|浏览(106)

我正在使用AVMutableComposition制作视频。我需要在不同的时间间隔添加文本覆盖。即。
1.显示字符串“abc”从0秒到2秒后隐藏
1.显示字符串“xyz”从1秒到1.5秒后隐藏
1.显示字符串“qwe”从2秒到5秒
我正在使用下面的代码添加文本覆盖,但它的静态和通过视频停留。

let parentLayer = CALayer()
parentLayer.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
let videoLayer = CALayer()
videoLayer.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)

let subtitleText = CATextLayer()
subtitleText.font = font
subtitleText.frame = CGRect(x: 0, y: 100, width: size.width, height: 50)
subtitleText.string = "hhh"
subtitleText.alignmentMode = kCAAlignmentCenter
subtitleText.foregroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1).cgColor
subtitleText.displayIfNeeded()

parentLayer.addSublayer(videoLayer)
parentLayer.addSublayer(subtitleText)

任何帮助是高度赞赏。

b5buobof

b5buobof1#

如果有人需要这个问题的答案,很抱歉我找不到一个直接的解决方案,所以我做了一个昂贵的工作。

  • 根据文本的时间范围修剪视频
  • 将文本添加到修剪的视频
  • 然后把那些碎片合并回去
6mzjoqzu

6mzjoqzu2#

CALayer上使用CABasicAnimation,指定AVMutableComposition的呈现时间范围:

/// Build animation for property
/// - keyPath: animatable property key path
/// - fromValue: value to animate from, previous is used for `nil`
/// - toValue: value to animate to
/// - atTime: start time in seconds
/// - duration: animation duration
func animate(_ keyPath: String, fromValue: Any? = nil, toValue: Any?, atTime: CFTimeInterval = 0.0, duration: CFTimeInterval = 0.0) -> CABasicAnimation {
    let animation = CABasicAnimation(keyPath: keyPath)
    animation.duration = duration
    animation.fromValue = fromValue
    animation.toValue = toValue
    animation.beginTime = atTime
    animation.isRemovedOnCompletion = false // to keep animated value after animation finished
    animation.fillMode = .forwards
    return animation
}

要显示CATextLayer1.5 秒到 3.0 秒,请用途:

subtitleText.opacity = 0.0
subtitleText.add(animate("opacity", toValue: 1.0, atTime: 1.5), forKey: "animateFadeIn")
subtitleText.add(animate("opacity", toValue: 0.0, atTime: 3.0), forKey: "animateFadeOut")

相关问题