Max/Min Scale of Pinch Zoom in UIPinchGestureRecognizer - iPhone iOS

后端 未结 10 1113
[愿得一人]
[愿得一人] 2020-11-29 17:29

How would I be able to limit the scale of the UIPinchGestureRecognizer to a min and max level? The scale property below seems to be relative to the last known scale (the de

10条回答
  •  孤街浪徒
    2020-11-29 18:02

    Here is the solution that I figured out after using Anomie's answer as a starting point.

    - (void)handlePinchGesture:(UIPinchGestureRecognizer *)gestureRecognizer {
    
        if([gestureRecognizer state] == UIGestureRecognizerStateBegan) {
            // Reset the last scale, necessary if there are multiple objects with different scales
            lastScale = [gestureRecognizer scale];
        }
    
        if ([gestureRecognizer state] == UIGestureRecognizerStateBegan || 
            [gestureRecognizer state] == UIGestureRecognizerStateChanged) {
    
            CGFloat currentScale = [[[gestureRecognizer view].layer valueForKeyPath:@"transform.scale"] floatValue];
    
            // Constants to adjust the max/min values of zoom
            const CGFloat kMaxScale = 2.0;
            const CGFloat kMinScale = 1.0;
    
            CGFloat newScale = 1 -  (lastScale - [gestureRecognizer scale]); 
            newScale = MIN(newScale, kMaxScale / currentScale);   
            newScale = MAX(newScale, kMinScale / currentScale);
            CGAffineTransform transform = CGAffineTransformScale([[gestureRecognizer view] transform], newScale, newScale);
            [gestureRecognizer view].transform = transform;
    
            lastScale = [gestureRecognizer scale];  // Store the previous scale factor for the next pinch gesture call  
        }
    }
    

提交回复
热议问题