简体   繁体   中英

Add gesture pinch zoom to camera preview layer, iOS, Swift

I am trying to add a pinch zoom to camera preview layer that is added programmatically. I have this code below as a function but that is all I have, from tips. I don't have any other code relating to it. I cannot find any more info around they all seem to focus on still images.

override func viewDidLoad() {
    super.viewDidLoad()

    let pinchRecognizer = UIPinchGestureRecognizer(target: self, action:#selector(pinch(_:)))

    pinchRecognizer.delegate = self
    self.cameraPreviewlayer.addGestureRecognizer(pinchRecognizer)

}

I get an error on this line

self.cameraPreviewlayer.addGestureRecognizer(pinchRecognizer)

it says cameraPreviewLayer does not have add geture.

Here is the function.

@objc func pinch(_ pinch: UIPinchGestureRecognizer) {

    let device = videoDeviceInput.device

    // Return zoom value between the minimum and maximum zoom values
    func minMaxZoom(_ factor: CGFloat) -> CGFloat {
        return min(min(max(factor, minimumZoom), maximumZoom), device.activeFormat.videoMaxZoomFactor)
    }

    func update(scale factor: CGFloat) {
        do {
            try device.lockForConfiguration()
            defer { device.unlockForConfiguration() }
            device.videoZoomFactor = factor
        } catch {
            print("\(error.localizedDescription)")
        }
    }

    let newScaleFactor = minMaxZoom(pinch.scale * lastZoomFactor)

    switch pinch.state {
    case .began: fallthrough
    case .changed: update(scale: newScaleFactor)
    case .ended:
        lastZoomFactor = minMaxZoom(newScaleFactor)
        update(scale: lastZoomFactor)
    default: break
    }
}

I was able to fix this.

All I had to do was move the

 let pinchRecognizer = UIPinchGestureRecognizer(target: self, action:#selector(pinch(_:)))

pinchRecognizer.delegate = self
self.cameraPreviewlayer.addGestureRecognizer(pinchRecognizer)

from view did load to where I set up the camera preview layer.

    cameraPreviewlayer = AVCaptureVideoPreviewLayer(session: captureSession)
    cameraPreviewlayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
    cameraPreviewlayer?.connection?.videoOrientation = AVCaptureVideoOrientation.portrait
    cameraPreviewlayer?.frame = self.view.frame
    //      scanArea.setRegionOfInterestWithProposedRegionOfInterest(regionOfInterest)
    self.view.layer.insertSublayer(cameraPreviewlayer!, at: 0)
    let pinchRecognizer = UIPinchGestureRecognizer(target: self, action:#selector(pinch(_:)))

    pinchRecognizer.delegate = self
    self.view.addGestureRecognizer(pinchRecognizer)

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