简体   繁体   中英

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!)```

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM