How to crop video into square iOS with AVAssetWrit

2020-05-24 08:47发布

问题:

I'm using AVAssetWriter to record a video and I want to be able to crop the video into a square with a offset from the top. Here is my code -

NSDictionary *videoCleanApertureSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                                            @320, AVVideoCleanApertureWidthKey,
                                            @320, AVVideoCleanApertureHeightKey,
                                            @10, AVVideoCleanApertureHorizontalOffsetKey,
                                            @10, AVVideoCleanApertureVerticalOffsetKey,
                                            nil];


NSDictionary *videoAspectRatioSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                                          @3, AVVideoPixelAspectRatioHorizontalSpacingKey,
                                          @3,AVVideoPixelAspectRatioVerticalSpacingKey,
                                          nil];



NSDictionary *codecSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                               [NSNumber numberWithInteger:bitsPerSecond], AVVideoAverageBitRateKey,
                               @1,AVVideoMaxKeyFrameIntervalKey,
                               videoCleanApertureSettings, AVVideoCleanApertureKey,
                               //AVVideoScalingModeFit,AVVideoScalingModeKey,
                               videoAspectRatioSettings, AVVideoPixelAspectRatioKey,
                               nil];

NSDictionary *videoCompressionSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                               AVVideoCodecH264, AVVideoCodecKey,
                               codecSettings,AVVideoCompressionPropertiesKey,
                               @320, AVVideoWidthKey,
                               @320, AVVideoHeightKey,
                               nil];

Whenever I uncomment the AVVideoScalingModeKey, the my assetWriter gives me an error about not being able to apply the videoCompressionSettings. I tried using How do make a reduced size video using AVAssetWriter? but it still didn't work for me.

回答1:

I added the AVVideoScalingModeFit,AVVideoScalingModeKey to my videoCompressionSettings to get it to work.