调整视频大小并保持1:1的比例

时间:2016-05-10 03:25:38

标签: ios swift core-graphics calayer avvideocomposition

我有一个800x800的视频,我想用375x375转换这个视频。

它应该是这样的: enter image description here

但最终的结果是: enter image description here

我做错了什么?

我的代码:

  let mixComposition = AVMutableComposition()

  // 2 - Create video tracks
  let compositionVideoTrack = mixComposition.addMutableTrackWithMediaType(AVMediaTypeVideo, preferredTrackID: Int32(kCMPersistentTrackID_Invalid))
  let clipVideoTrack = videoAsset.tracksWithMediaType(AVMediaTypeVideo)[0]

  do {
      try compositionVideoTrack.insertTimeRange(CMTimeRangeMake(kCMTimeZero, videoAsset.duration), ofTrack: clipVideoTrack, atTime: kCMTimeZero)
  } catch _ {

  }
  clipVideoTrack.preferredTransform

  // Video size
  let videoSize = clipVideoTrack.naturalSize
  let scale = imageLayer.frame.size.width / videoSize.width
  let scaledSize = CGSizeMake(videoSize.width * scale, videoSize.height * scale)
  let transform = CGAffineTransformMakeScale(scale, scale)

  // sorts the layer in proper order and add title layer
  let parentLayer = CALayer()
  let videoLayer = CALayer()
  parentLayer.frame = CGRectMake(0, 0, imageLayer.frame.size.width, imageLayer.frame.size.height)
  videoLayer.frame = CGRectMake(0, 0, imageLayer.frame.size.width, imageLayer.frame.size.height)
  parentLayer.addSublayer(videoLayer)
  parentLayer.addSublayer(imageLayer)

  let videoComp = AVMutableVideoComposition()
  videoComp.renderSize = scaledSize
  videoComp.frameDuration = CMTimeMake(1, 30)
  videoComp.animationTool = AVVideoCompositionCoreAnimationTool(postProcessingAsVideoLayer: videoLayer, inLayer: parentLayer)

  /// instruction
  let instruction = AVMutableVideoCompositionInstruction()
  instruction.timeRange = CMTimeRangeMake(kCMTimeZero, mixComposition.duration)
  //let videoTrack = mixComposition.tracksWithMediaType(AVMediaTypeVideo)[0]

  //let layerInstruction = self.videoCompositionInstructionForTrack(compositionVideoTrack, asset: videoAsset)

  let layerInstruction = AVMutableVideoCompositionLayerInstruction(assetTrack: clipVideoTrack)
  layerInstruction.setTransform(transform, atTime: kCMTimeZero)

  instruction.layerInstructions = [layerInstruction]
  videoComp.instructions = [instruction]

1 个答案:

答案 0 :(得分:0)

这是由于

之间的微小计算差异
let scaledSize = CGSizeMake(videoSize.width * scale, videoSize.height * scale)
let transform = CGAffineTransformMakeScale(scale, scale)

解决方案是将缩放尺寸减小2 px

let scaledSize = CGSizeMake(videoSize.width * scale - 2, videoSize.height * scale - 2)
let transform = CGAffineTransformMakeScale(scale, scale)