我试图在电影中插入文字图层(CATextLayer
)。首先,让我将文本图层(CATextLayer
)插入有线NSView
对象,例如
let myLayer = CALayer()
let textLayer = CATextLayer()
let text = "Hello, Mr. Jordan. How are you doing?"
let attributedString = MakeAttributedString.makeRegularCenterAttributedString(text: text, fsize: 64.0, color: NSColor.green) // A class function for creating an NSAttributedString
textLayer.string = attributedString
textLayer.isWrapped = true
textLayer.backgroundColor = NSColor.black.withAlphaComponent(0.9).cgColor
textLayer.cornerRadius = 10.0
textLayer.frame = CGRect(x: 100, y: 200, width: 600, height: 200)
myLayer.addSublayer(textLayer)
myView.layer?.addSublayer(myLayer) // myView is a wired `NSView` object laid over a wired `videoPlayer` object
好。我在视图中插入CATextLayer
。现在,我尝试使用AVMutableVideoComposition
执行相同操作,使用CATextLayer
对象创建电影。
let parentLayer = CALayer()
parentLayer.isHidden = false
parentLayer.opacity = 1.0
parentLayer.frame = CGRect(x: 0, y: 0, width: 1280.0, height: 720.0)
parentLayer.addSublayer(videoLayer)
let myLayer = CALayer()
let textLayer = CATextLayer()
let text = "Hello, Mr. Jordan. How are you doing?"
let attributedString = MakeAttributedString.makeRegularCenterAttributedString(text: text, fsize: 64.0, color: NSColor.green)
textLayer.string = attributedString
textLayer.isWrapped = true
textLayer.backgroundColor = NSColor.black.withAlphaComponent(0.9).cgColor
textLayer.cornerRadius = 10.0
textLayer.frame = CGRect(x: 100, y: 200, width: 600, height: 200)
myLayer.addSublayer(textLayer)
parentLayer.addSublayer(myLayer)
let layerComposition = AVMutableVideoComposition()
layerComposition.frameDuration = CMTimeMake(1, 30)
layerComposition.renderSize = self.frameSize
layerComposition.animationTool = AVVideoCompositionCoreAnimationTool(postProcessingAsVideoLayer: videoLayer, in: parentLayer)
let instruction = AVMutableVideoCompositionInstruction()
instruction.timeRange = CMTimeRangeMake(kCMTimeZero, composition.duration)
let layerInstruction = AVMutableVideoCompositionLayerInstruction(assetTrack: videoTrack)
layerInstruction.setTransform(videoTrack.preferredTransform, at: kCMTimeZero)
instruction.layerInstructions = [layerInstruction] as [AVVideoCompositionLayerInstruction]
layerComposition.instructions = [instruction] as [AVVideoCompositionInstructionProtocol]
self.assetExport = AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetHighestQuality)
self.assetExport.outputFileType = AVFileType.mov
...
...
我得到了文本框的背景色。但文本字符串没有显示。我可以为电影添加音频和水印图像(CALayer
)。但文本字符串永远不会出现。为什么我永远不会以文本字符串结束?
修改
我已经使用Xcode 9.2在Sierra 10.12.6下测试了它。我还使用Xcode 9.4.1在High Sierra 10.13.4下进行了测试。文本字符串没有显示。当CABasicAnimation
的相同动画有效时,NSView
无法使用电影曲目运行。使用NSFont
或NSAttributedString
设置文字字符串会产生影响。