AVCaptureVideoPreviewLayer smooth orientation rotation

后端 未结 9 991
Happy的楠姐
Happy的楠姐 2021-02-02 16:45

I\'m trying to disable any discernable orientation rotation to an AVCaptureVideoPreviewLayer while still maintaining rotation for any subviews. AVCaptureVideoPreviewLayer does h

9条回答
  •  忘了有多久
    2021-02-02 17:10

    This is an old question, but since it didn't have an accepted answer and I've been dealing with this issue myself for the past several days, I figured I would post the answer.

    The trick to rotating the video based on device orientation changes, is to NOT ROTATE the AVCaptureVideoPreviewLayer or the AVCaptureConnection at all.

    Changing the orientation on the AVCaptureConnection ( AVCaptureVideoPreviewLayer's orientation was deprecated ) ALWAYS results in an ugly animated change .. And after the video is rotated, you would still have to transform the preview layer.

    The correct way to do this is use an AVAssetWriter to write the Video and Audio data .. and then apply a transform on the AVAssetWriterInput at the time that you start recording.

    Here is a blurb from Apple about this --

    Receiving rotated CVPixelBuffers from AVCaptureVideoDataOutput

    To request buffer rotation, a client calls -setVideoOrientation: on the AVCaptureVideoDataOutput's video AVCaptureConnection. Note that physically rotating buffers does come with a performance cost, so only request rotation if it's necessary. If, for instance, you want rotated video written to a QuickTime movie file using AVAssetWriter, it is preferable to set the -transform property on the AVAssetWriterInput rather than physically rotate the buffers in AVCaptureVideoDataOutput.

    The applying of the transform is similar to the code posted above.

    1. You register for device orientation changes.
    2. Keep track of transform to apply based on the new device orientation.
    3. When record is pressed, set up the AVAssetWriterInput and apply transform to it.

    Hope this helps whoever is looking for an answer.

提交回复
热议问题