Scanning 2D code for gesture to pull the lens closer and farther

Posted by pulkit123 on Sun, 12 Apr 2020 19:24:08 +0200

In the need to do scanner, there is often a need to magnify the lens.
Apple offers VieoScaleAndCropFactor in AVCaptureConnection: Zoom in and out the clipping factor, which allows you to zoom in and out of the lens.Combined with the gesture UIPinchGestureRecognizer, it is easy to pull the lens closer and farther with a gesture.

  1. Gesture code
///Scaling ratio for start of record
@property(nonatomic,assign)CGFloat beginGestureScale;

///Last zoom
@property(nonatomic,assign)CGFloat effectiveScale;

- (void)cameraInitOver
    if (self.isVideoZoom) {
        UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchDetected:)];
        pinch.delegate = self;
        [self.view addGestureRecognizer:pinch];

- (void)pinchDetected:(UIPinchGestureRecognizer*)recogniser
    self.effectiveScale = self.beginGestureScale * recogniser.scale;
    if (self.effectiveScale < 1.0){
        self.effectiveScale = 1.0;
    [self.scanObj setVideoScale:self.effectiveScale];


- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
    if ( [gestureRecognizer isKindOfClass:[UIPinchGestureRecognizer class]] ) {
        _beginGestureScale = _effectiveScale;
    return YES;
  1. Code for pulling closer and farther lens
- (void)setVideoScale:(CGFloat)scale
    [_input.device lockForConfiguration:nil];

    AVCaptureConnection *videoConnection = [self connectionWithMediaType:AVMediaTypeVideo fromConnections:[[self stillImageOutput] connections]];
    CGFloat maxScaleAndCropFactor = ([[self.stillImageOutput connectionWithMediaType:AVMediaTypeVideo] videoMaxScaleAndCropFactor])/16;

    if (scale > maxScaleAndCropFactor)
        scale = maxScaleAndCropFactor;

    CGFloat zoom = scale / videoConnection.videoScaleAndCropFactor;

    videoConnection.videoScaleAndCropFactor = scale;

    [_input.device unlockForConfiguration];

    CGAffineTransform transform = _videoPreView.transform;
    [CATransaction begin];
    [CATransaction setAnimationDuration:.025];

     _videoPreView.transform = CGAffineTransformScale(transform, zoom, zoom);

    [CATransaction commit];


One thing to note is that the videoScaleAndCropFactor property can be set to a value in the range of 1.0 to videoMaxScaleAndCropFactor, the videoScaleAndCropFactor property has a value range of 1.0-videoMaxScaleAndCropFactor, if you set it beyond the range, it will crash!