斯威夫特:方形video合成

我正在按照以下代码进行方形video合成

func completeWithVideoAtURL(input: NSURL) { let asset = AVAsset(url: input as URL) let output = NSURL(fileURLWithPath: NSHomeDirectory() + "/Documents/Video.mp4") let session = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetMediumQuality)! session.videoComposition = self.squareVideoCompositionForAsset(asset: asset) session.outputURL = output as URL session.outputFileType = AVFileTypeMPEG4 session.shouldOptimizeForNetworkUse = true session.exportAsynchronously(completionHandler: { () -> Void in DispatchQueue.main.async(execute: { () -> Void in // do something with the output print("\(output)") PHPhotoLibrary.shared().performChanges({ PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: output as URL) }) { saved, error in if saved { print("saved to gallery") } } }) }) } func squareVideoCompositionForAsset(asset: AVAsset) -> AVVideoComposition { let track = asset.tracks(withMediaType: AVMediaTypeVideo)[0] let length = max(track.naturalSize.width, track.naturalSize.height) var transform = track.preferredTransform let size = track.naturalSize let scale: CGFloat = (transform.a == -1 && transform.b == 0 && transform.c == 0 && transform.d == -1) ? -1 : 1 // check for inversion transform = transform.translatedBy(x: scale * -(size.width - length) / 2, y: scale * -(size.height - length) / 2) let transformer = AVMutableVideoCompositionLayerInstruction(assetTrack: track) transformer.setTransform(transform, at: kCMTimeZero) let instruction = AVMutableVideoCompositionInstruction() instruction.timeRange = CMTimeRange(start: kCMTimeZero, duration: kCMTimePositiveInfinity) instruction.layerInstructions = [transformer] let composition = AVMutableVideoComposition() composition.frameDuration = CMTime(value: 1, timescale: 30) composition.renderSize = CGSize(width: length, height: length) composition.instructions = [instruction] return composition } 

squareVideoCompositionForAsset()函数我获取track.naturalSize.widthtrack.naturalSize.height之间的最大 长度值因为我不想裁剪video的任何部分部分。 如果我采用最小值,对于纵向video,它会裁剪video的上部和下部,而对于横向video,它会裁剪video的左右部分。

  • 对于风景video,输出是可以的

在此处输入图像描述

  • 但对于肖像video,输出就像下面的图像

在此处输入图像描述

video左侧。 是否可以将video居中? 对于长时间的解释,任何帮助都会很棒。

而不是这条线

let scale:CGFloat =(transform.a == -1 && transform.b == 0 && transform.c == 0 && transform.d == -1)? -1:1

我刚用过这个

  var scale = CGFloat() if (transform.a == 0 && transform.b == 1 && transform.c == -1 && transform.d == 0) { scale = -1 } else if (transform.a == 0 && transform.b == -1 && transform.c == 1 && transform.d == 0) { scale = -1 } else if (transform.a == 1 && transform.b == 0 && transform.c == 0 && transform.d == 1) { scale = 1 } else if (transform.a == -1 && transform.b == 0 && transform.c == 0 && transform.d == -1) { scale = 1 } 

它就像一个魅力