swiftuigesturerecognizeravcapturesessionavcapturedevice

zoom in and zoom out camera on pinch gesture swift


I am using front camera in my app. I want that while taking photos user can zoom in and out camera

I tried this code

let device = AVCaptureDevice.default(for: .video)
print(sender.scale)
let vZoomFactor = sender.scale * prevZoomFactor
if sender.state == .ended {
    prevZoomFactor = vZoomFactor >= 1 ? vZoomFactor : 1
}

if sender.state == .changed{
    do {
        try device!.lockForConfiguration()
        if (vZoomFactor <= device!.activeFormat.videoMaxZoomFactor) {
            device!.videoZoomFactor = max(1.0, min(vZoomFactor, device!.activeFormat.videoMaxZoomFactor))
            device?.unlockForConfiguration()
        } else {
            print("Unable to set videoZoom: (max \(device!.activeFormat.videoMaxZoomFactor), asked \(vZoomFactor))")
        }
    } catch {
        print("\(error.localizedDescription)")
    }
}

every thing is working fine in back camera but zoom is not applying on front camera.


Solution

  • well, after spending hours on this code i got the there where i was making the mistake.

    let device = AVCaptureDevice.default(for: .video)
    

    this will by default get the back camera and work perfect but when i switch it to front it is till considering it as back camera , so i just added a condition

        if  currentcam == frontcam {
          let device = frontcam
          //did other stuff for zooimng
         } 
    
       else {
         let device = AVCaptureDevice.default(for: .video)
         //did other stuff for zooimng
      }
    

    this worked fine for me