How do I use AVFoundation to crop a video

前端 未结 2 1568
独厮守ぢ
独厮守ぢ 2020-11-28 03:39

I\'m trying to use AVFoundation to crop videos I\'m recording. So lets say i create a AVCaptureVideoPreviewLayer and set the frame to be 300x300.

AVCaptureVi         


        
相关标签:
2条回答
  • 2020-11-28 04:18

    ios7 added a specific Layer instruction just for cropping.

    videolayerInstruction setCropRectangle:atTime:
    

    _mike

    0 讨论(0)
  • 2020-11-28 04:19

    Soemthing like this. 99% of this code just sets it up to do a custom CGAffineTransform, and then save out the result.

    I'm assuming that you want the cropped video to take up full size/width of the output - so that e.g a Scale Affine is the correct solution (you zoom in on the video, giving the effect of having cropped + resized).

    AVAsset* asset = // your input
    
    AVAssetTrack *clipVideoTrack = [[asset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0];
    
    AVMutableVideoComposition* videoComposition = [[AVMutableVideoComposition videoComposition]retain];
    videoComposition.renderSize = CGSizeMake(320, 240);
    videoComposition.frameDuration = CMTimeMake(1, 30);
    
    AVMutableVideoCompositionInstruction *instruction = [AVMutableVideoCompositionInstruction videoCompositionInstruction];
    instruction.timeRange = CMTimeRangeMake(kCMTimeZero, CMTimeMakeWithSeconds(60, 30) );
    
    AVMutableVideoCompositionLayerInstruction* transformer = [AVMutableVideoCompositionLayerInstruction videoCompositionLayerInstructionWithAssetTrack:clipVideoTrack];
    CGAffineTransform finalTransform = // setup a transform that grows the video, effectively causing a crop
        [transformer setTransform:finalTransform atTime:kCMTimeZero];
        instruction.layerInstructions = [NSArray arrayWithObject:transformer];
    videoComposition.instructions = [NSArray arrayWithObject: instruction];
    
    exporter = [[AVAssetExportSession alloc] initWithAsset:saveComposition presetName:AVAssetExportPresetHighestQuality] ;
    exporter.videoComposition = videoComposition;
    exporter.outputURL=url3;
    exporter.outputFileType=AVFileTypeQuickTimeMovie;
    
    [exporter exportAsynchronouslyWithCompletionHandler:^(void){}];
    
    0 讨论(0)
提交回复
热议问题