2

enter image description here

I'm using AVFoundation to do some video recording and I've looked all over for how to get the video to aspect fill. I've read through avfoundation guide by apple and class referene for AVCaptureVideoPreviewLayer. I also read this question here AVFoundation camera preview layer not working . Here is my code

        videoPreviewLayer.frame = captureView.frame
        videoPreviewLayer.frame.origin = CGPoint(x: 0, y: 0)
        videoPreviewLayer.backgroundColor = UIColor.redColor().CGColor
        videoPreviewLayer.contentsGravity = AVLayerVideoGravityResizeAspectFill
        videoPreviewLayer.masksToBounds = true
        captureView.layer.addSublayer(videoPreviewLayer)

I put this in viewDidLayoutSubviews() so that I can get the correct size for captureView.frame which is the UIView my previewLayer is inside of. Any clue why aspectFill isn't working? As you can see from the red background the layer is the correct size but the contentsGravity isn't filling the layer.

Community
  • 1
  • 1
NSGangster
  • 2,397
  • 12
  • 22

2 Answers2

8

Found my answer in this link AVCaptureVideoPreviewLayer . I needed to use videoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill instead of videoPreviewLayer.contentsGravity = AVLayerVideoGravityResizeAspectFill

Community
  • 1
  • 1
NSGangster
  • 2,397
  • 12
  • 22
1

For me, the answer for my problem was provided by NSGangster in the question:

I put this in viewDidLayoutSubviews() so that I can get the correct size for captureView.frame which is the UIView my previewLayer is inside of.

I originally had the code in viewDidLoad() which meant the layer was resizing before the true bounds of the view was determined.

Thanks for sharing.

JCutting8
  • 732
  • 9
  • 29