majindageta
8/1/2018 - 12:59 PM

Pinch Gesture - Limit size

Handle pinch gesture limiting size

- (void)handlePinch:(UIPinchGestureRecognizer *)recognizer {
    if (UIGestureRecognizerStateBegan == recognizer.state ||
        UIGestureRecognizerStateChanged == recognizer.state) {
        
        // Use the x or y scale, they should be the same for typical zooming (non-skewing)
        float currentScale = [[recognizer.view.layer valueForKeyPath:@"transform.scale.x"] floatValue];
        
        // Variables to adjust the max/min values of zoom
        float minScale = 0.7;
        float maxScale = 2.0;
        float zoomSpeed = .5;
        
        float deltaScale = recognizer.scale;
        
        // You need to translate the zoom to 0 (origin) so that you
        // can multiply a speed factor and then translate back to "zoomSpace" around 1
        deltaScale = ((deltaScale - 1) * zoomSpeed) + 1;
        
        // Limit to min/max size (i.e maxScale = 2, current scale = 2, 2/2 = 1.0)
        //  A deltaScale is ~0.99 for decreasing or ~1.01 for increasing
        //  A deltaScale of 1.0 will maintain the zoom size
        deltaScale = MIN(deltaScale, maxScale / currentScale);
        deltaScale = MAX(deltaScale, minScale / currentScale);
        
        CGAffineTransform zoomTransform = CGAffineTransformScale(recognizer.view.transform, deltaScale, deltaScale);
        recognizer.view.transform = zoomTransform;
        
        // Reset to 1 for scale delta's
        //  Note: not 0, or we won't see a size: 0 * width = 0
        recognizer.scale = 1;
    }
}