Search code examples
iosswiftxcodeuikitavfoundation

How To Center VideoPreviewLayer in Custom UIView (Storyboard Swift)


How do I center a videoPreviewLayer in an existing UIView?? I have tried the following, but it is smaller than how I want.



        var videoPreviewLayer : AVCaptureVideoPreviewLayer?

        let captureDevice = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back)
        do {
            let input = try AVCaptureDeviceInput(device: captureDevice!)
            captureSession = AVCaptureSession()
            captureSession?.addInput(input)
            videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession!)
//            let frame : CGRect = self.scanView.layer.bounds
//            videoPreviewLayer?.frame = frame
            videoPreviewLayer?.frame = self.scanView.bounds
//            videoPreviewLayer?.bounds = self.view.bounds

            scanView.layer.addSublayer(videoPreviewLayer!)
            captureSession?.startRunning()
        } catch {
            print("error-jz")
        }

        capturePhotoOutput = AVCapturePhotoOutput()
        capturePhotoOutput?.isHighResolutionCaptureEnabled = true
        captureSession?.addOutput(capturePhotoOutput!)```

Solution

  • It should be centered in whatever view you add your videoPreviewLayer to. However when you said it is smaller than you want, that may be because you are not setting the video gravity for the player layer.

    videoPreviewLayer.videoGravity = .resizeAspectFill
    

    This will make the video preview fill the entire view it encompasses. If its still not centered the way you want it, you might have to fix the centering of the UIView itself.