Search code examples
ioscameraswift4uiviewanimationtransition

Add transition in custom camera


I am implementing a custom camera. All is working perfectly. I want to add transition while switching from front to back and vice versa. Here is my code.

      @IBAction func switchCamera(_ sender: Any) {

        captureSession.beginConfiguration()
        let newDevice = (currentDevice?.position == AVCaptureDevice.Position.back) ? frontCamera : backCamera
        for input in captureSession.inputs {
            captureSession.removeInput(input as! AVCaptureDeviceInput)
        }
        let cameraInput:AVCaptureDeviceInput
        do {
            cameraInput = try AVCaptureDeviceInput(device: newDevice!)
        } catch {
            print(error)
            return
        }
        if captureSession.canAddInput(cameraInput) {
            captureSession.addInput(cameraInput)
        }
        currentDevice = newDevice
        captureSession.commitConfiguration()
    }

I want to add to add smooth animation while sided of camera are switching.(Similar to how we navigate from one ViewController to other).

How can I implement this?


Solution

  • You can use a UIView behind the camera view with clear background colour and then add transition to that view while switching the camera from back to front or vice-versa. Do it with declaring a @IBOutlet of a UIView or programmatically and then on switch use this: Hope it will help.

    UIView.transition(with: yourView,
                         duration: 0.5,
                         options: [.transitionFlipFromRight], // change type accordingly
                         animations: {
    
                           // do your stuff
       },
                         completion: nil)