Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AVCaptureSession and Preview Layer does not fill entire screen

So, I'm trying to use the camera on my phone in my app, and I was successful, but unfortunately, when using the preview, the layer does not fill the entire screen Here is an image to show you what it looks like

Here's my code:

if let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) {
        self.previewLayer = previewLayer
        self.view.layer.addSublayer(self.previewLayer)
        self.previewLayer.frame = self.view.layer.frame
        captureSession.startRunning()

        let dataOutput = AVCaptureVideoDataOutput()
        dataOutput.videoSettings = [(kCVPixelBufferPixelFormatTypeKey as NSString):NSNumber(value:kCVPixelFormatType_32BGRA)]

        dataOutput.alwaysDiscardsLateVideoFrames = true

        if captureSession.canAddOutput(dataOutput) {
            captureSession.addOutput(dataOutput)
        }

        captureSession.commitConfiguration()


        let queue = DispatchQueue(label: "com.Osmo.captureQueue")
        dataOutput.setSampleBufferDelegate(self, queue: queue)
    }
like image 384
Arya K Avatar asked Jan 05 '23 12:01

Arya K


2 Answers

This may happen because you're trying to set a preview layer's frame from view which has auto layout constraints. Try to add an override of viewDidLayoutSubviews method to your view controller:

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    self.previewLayer.frame = self.view.layer.bounds
}
like image 101
ninjaproger Avatar answered Jan 28 '23 15:01

ninjaproger


Please try the following:

if let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) {
        self.previewLayer = previewLayer
        self.previewLayer.frame = self.view.bounds
        self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
        self.view.layer.insertSublayer(self.previewLayer, at: 0)
        captureSession.startRunning()

        let dataOutput = AVCaptureVideoDataOutput()
        dataOutput.videoSettings = [(kCVPixelBufferPixelFormatTypeKey as NSString):NSNumber(value:kCVPixelFormatType_32BGRA)]

        dataOutput.alwaysDiscardsLateVideoFrames = true

        if captureSession.canAddOutput(dataOutput) {
            captureSession.addOutput(dataOutput)
        }

        captureSession.commitConfiguration()


        let queue = DispatchQueue(label: "com.Osmo.captureQueue")
        dataOutput.setSampleBufferDelegate(self, queue: queue)
    }
like image 31
manishg Avatar answered Jan 28 '23 13:01

manishg