gpt4 book ai didi

ios - 使用 swift 将视频裁剪并导出为圆形

转载 作者:行者123 更新时间:2023-11-28 08:27:29 27 4
gpt4 key购买 nike

我想在“圆圈”中裁剪视频并存储它。这是我到目前为止所做的。但问题是它只以矩形裁剪视频。我想把它裁剪成圆形。我该怎么做?

    func cropVideo() {

let asset = AVAsset.init(url: URL(fileURLWithPath: Bundle.main.path(forResource: "1", ofType: "mp4")!))
let clipVideoTrack = asset.tracks(withMediaType: AVMediaTypeVideo)[0]
let videoComposition = AVMutableVideoComposition()
videoComposition.frameDuration = CMTimeMake(1, 30)
videoComposition.renderSize = CGSize(width: clipVideoTrack.naturalSize.height, height: clipVideoTrack.naturalSize.height)
let instruction = AVMutableVideoCompositionInstruction()
instruction.timeRange = CMTimeRangeMake(kCMTimeZero, CMTimeMakeWithSeconds(60, 30))
let transformer = AVMutableVideoCompositionLayerInstruction.init(assetTrack: clipVideoTrack)
let t1 = CGAffineTransform(translationX: clipVideoTrack.naturalSize.height, y: 0)
let t2 = t1.rotated(by: CGFloat(M_PI_2))
let finalTransform = t2
transformer.setTransform(finalTransform, at: kCMTimeZero)
instruction.layerInstructions = [transformer]
videoComposition.instructions = [instruction]


let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let exportPath = documentsPath.appendingFormat("/CroppedVideo.mp4")
let exportUrl = URL(fileURLWithPath: exportPath)
print("export url = \(exportUrl)")


do {
try FileManager.default.removeItem(at: exportUrl)
}
catch _ {
}

exporter = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetHighestQuality)
exporter.videoComposition = videoComposition
exporter.outputURL = exportUrl
exporter.outputFileType = AVFileTypeQuickTimeMovie
exporter.exportAsynchronously(completionHandler: {() -> Void in
DispatchQueue.main.async(execute: {() -> Void in
self.exportDidFinish(self.exporter)
})
})
}

func exportDidFinish(_ session: AVAssetExportSession) {
let outputURL = session.outputURL
print("outputurl = \(outputURL)")

}

最佳答案

假设我上面的问题是正确的,诀窍是使用 mask 和圆形图像而不是使用 CGAffineTransform。我怀疑有一种方法可以使用 CGAffineTransform 来实现,但与此同时......

  • 做一张中间有透明圆圈的图片
  • 将其导入您的项目并加载
  • 先添加视频层,然后添加 mask 图像
  • 导出

这应该可以满足您的需求。关于这个 here 有一个稍旧的教程,往下看大约一半。

关于ios - 使用 swift 将视频裁剪并导出为圆形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39625653/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com