AVCaptureDevice Camera Zoom

前端 未结 9 607
没有蜡笔的小新
没有蜡笔的小新 2021-01-31 19:51

I have a simple AVCaptureSession running to get a camera feed in my app and take photos. How can I implement the \'pinch to zoom\' functionality using a UIGestureRecognize

9条回答
  •  醉酒成梦
    2021-01-31 20:20

    I started from the @Gabriel Cartier's solution (thanks). In my code I've preferred to use the smoother rampToVideoZoomFactor and a simpler way to compute the device's scale factor.

    (IBAction) pinchForZoom:(id) sender forEvent:(UIEvent*) event {
        UIPinchGestureRecognizer* pinchRecognizer = (UIPinchGestureRecognizer *)sender;
    
        static CGFloat zoomFactorBegin = .0;
        if ( UIGestureRecognizerStateBegan == pinchRecognizer.state ) {
            zoomFactorBegin = self.captureDevice.videoZoomFactor;
    
        } else if (UIGestureRecognizerStateChanged == pinchRecognizer.state) {
            NSError *error = nil;
            if ([self.captureDevice lockForConfiguration:&error]) {
    
                CGFloat desiredZoomFactor = zoomFactorBegin * pinchRecognizer.scale;
                CGFloat zoomFactor = MAX(1.0, MIN(desiredZoomFactor, self.captureDevice.activeFormat.videoMaxZoomFactor));
                [self.captureDevice rampToVideoZoomFactor:zoomFactor withRate:3.0];
    
                [self.captureDevice unlockForConfiguration];
            } else {
                NSLog(@"error: %@", error);
            }
        }
    }
    

提交回复
热议问题