How to set minimum and maximum zoom scale using UIPinchGestureRecognizer

TheTiger picture TheTiger · Jun 9, 2012 · Viewed 9.2k times · Source

I want to zoom in and zoom out an image view and i dont want to use UIScrollView for that. so for this i used UIPinchGestureRecognizer and here is my code -

[recognizer view].transform = CGAffineTransformScale([[recognizer view] transform], [recognizer scale], [recognizer scale]);
recognizer.scale = 1;

this is working fine for zoom in and zoom out. But problem is that i want to zoom in and zoom out in specific scale like in UIScrollView we can set the maxZoom and minZoom. i could not found any solution for that, every tutorial about UIPinchGestureRecognizer just describe the same code.

Answer

nhahtdh picture nhahtdh · Jun 9, 2012

Declare 2 ivars CGFloat __scale and CGFloat __previousScale in the interface of the class that handles the gesture. Set __scale to 1.0 by overriding one of the init functions (make sure to call the super constructor here).

- (void)zoom:(UIPinchGestureRecognizer *)gesture { 
    NSLog(@"Scale: %f", [gesture scale]);

    if ([gesture state] == UIGestureRecognizerStateBegan) {
        __previousScale = __scale;
    }

    CGFloat currentScale = MAX(MIN([gesture scale] * __scale, MAX_SCALE), MIN_SCALE);  
    CGFloat scaleStep = currentScale / __previousScale;
    [self.view setTransform: CGAffineTransformScale(self.view.transform, scaleStep, scaleStep)];

    __previousScale = currentScale;

    if ([gesture state] == UIGestureRecognizerStateEnded || 
        [gesture state] == UIGestureRecognizerStateCancelled ||
        [gesture state] == UIGestureRecognizerStateFailed) {
        // Gesture can fail (or cancelled?) when the notification and the object is dragged simultaneously
        __scale = currentScale;
        NSLog(@"Final scale: %f", __scale);
    }
}