AVCaptureVideoPreviewLayer creating 2 views when resizing

208 Views Asked by At

I have made a Camera object that I am attaching on a CameraViewController. The Camera object has the following method inside, which sets the AVCaptureVideoPreviewLayer on a given view controller.

func displayPreview(on view: UIView) throws {
        guard let captureSession = self.captureSession, captureSession.isRunning else {
            throw CameraControllerError.captureSessionIsMissing
        }

        previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
        view.layer.insertSublayer(self.previewLayer!, at: 0)
        previewLayer?.frame = view.bounds
        previewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
        previewLayer?.connection?.videoOrientation = .portrait
        previewLayer?.masksToBounds = true
    }

In the CameraViewController, to set the camera object, I am doing the following

var camera = Camera()

override func viewDidLoad() {
        super.viewDidLoad()
        configureView()
    }


    override func viewWillLayoutSubviews() {
        try? self.camera.displayPreview(on: self.view)
    }


    private func configureView(){
        self.view.addTapGestureRecognizer(action: {
            if let parentView = self.parent?.view.frame{
                UIView.animate(withDuration: 0.4, animations: {
                    self.view.layer.cornerRadius = 0
                    self.view.layer.masksToBounds = true
                    self.view.layer.borderWidth = 0
                    self.view.frame = parentView
                }, completion: nil)
            }
        })
    } 

It all works well, to the point the view is resizing. When this happens, it looks like the camera is creating 2 views, like in the picture, an older one on the top and an updated one view's size. Not only that, but when the view resizes, it looks like the previewLayer reloads before resizing (it takes a bit before the bigger view appears). What I am trying to achieve is a continuous animated camera preview resize view. What do I need to change in my code? I've been playing with placing try? self.camera.displayPreview(on: self.view) in different view load parts, but that did not change anything.

enter image description here

0

There are 0 best solutions below