Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AVCaptureVideoPreviewLayer not filling the fullscreen

Tags:

ios

swift

I am trying to do a snapchat like camera view, with the camera stream filling all the screen.

Here is the code :

func beginSession() {
    var err : NSError? = nil

    // try to open the device
    let videoCapture = AVCaptureDeviceInput(device: captureDevice, error: &err)

    if err != nil {
        // Fail silently.  Do better in the real world.
        println("Capture session could not start: \(err?.description)")
        return
    }

    // add video input
    if captureSession.canAddInput(videoCapture) {
        captureSession.addInput(videoCapture)
    }

    // config capture session
    if !captureSession.running {
        // set JPEG output
        stillImageOutput = AVCaptureStillImageOutput()
        let outputSettings = [ AVVideoCodecKey : AVVideoCodecJPEG ]
        stillImageOutput!.outputSettings = outputSettings

        // add output to session
        if captureSession.canAddOutput(stillImageOutput) {
            captureSession.addOutput(stillImageOutput)
        }

        // display camera in UI
        let bounds = cameraView.bounds
        previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
        previewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
        previewLayer?.frame = CGRectMake(CGRectGetMinX(bounds), CGRectGetMinY(bounds), cameraView.frame.width, cameraView.frame.height)
        cameraView.layer.addSublayer(previewLayer)

        println(cameraView.frame.height)
        println(previewLayer?.frame.height)
        // start camera
        captureSession.startRunning()
    }
}

I call begin session in the viewDidAppear to be sure all the view settings are applied and i set the necessary constraints on the cameraView to be sure it fills the screen.

When I check my logs, I can see that previewLayer and cameraView have the same dimensions and position.

Here is how it renders :

enter image description here

Here is the incriminated view controller :

like image 665
Hadrien Pierre Mazelier Avatar asked Jul 07 '15 09:07

Hadrien Pierre Mazelier


1 Answers

Seems like the cameraView frame is not set while you are adding the preview layer frame.

pls try to update the preview layers frame in viewDidLayoutSubviews() function

like image 102
Sujith Chandran Avatar answered Oct 05 '22 07:10

Sujith Chandran