简体   繁体   中英

Resize video and keeping 1:1 scale

I have a 800x800 video and I want to transform this video in 375x375.

It should looks like this: 在此输入图像描述

But the final result is it: 在此输入图像描述

What am I doing wrong?

My Code:

  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]

This is due to minor calculation difference between

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

The solution is to decrease the scaled size by 2 px

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM