Search code examples
iosviewstoryboardconstraintsaddsubview

AVCaptureVideoPreviewLayer appears to be escaping parent bounds


I'm having an issue fitting a AVCaptureVideoPreviewLayer inside its parents bounds.

Here is the contextual code:

    capturePreview = AVCaptureVideoPreviewLayer(session: captureSession)
    guard let capturePreview = capturePreview else { return }

When I have

   capturePreview.frame = cameraView.bounds
   cameraView.layer.addSublayer(capturePreview)

The following occurs:

enter image description here

And when I have

capturePreview.bounds = cameraView.layer.bounds
cameraView.layer.addSublayer(capturePreview)

this happens enter image description here

I'm trying to get the preview layer to fit inside the black box in the next picture

enter image description here

From what I have seen in the documentation, I'm not sure where I am going wrong. Thanks for any help. For reference I will add the constraints I gave in storyboard.

enter image description here


Solution

  • Have you tried using something like:

    capturePreview.frame = cameraView.bounds
    cameraView.layer.addSublayer(capturePreview)
    cameraView.clipsToBounds = true