简体   繁体   中英

iOS: Zoom using Pinch gesture with inertia and overhead

I am fairly new to iOS and I am trying to figure out how to use a Pinch gesture to zoom with inertia and overhead (I do not know if the word overhead is correct in this context, in german it would be called "Überschwingen").

Basically what it shall do: It should have a max and min scale (in my case 1.0 to 4.0) in which you can zoom. When the gesture is finished it should take the given velocity and make a curve out animation, also allowing the view to over- and underflow the given scales and then move back to the min or max like with tension.

I got the Gesture Recognizer running for this and also managed to get it make use of my minimum and maximum scale (using examples from stackoverflow). This is what I got so far:

- (void)handle_pinch:(UIPinchGestureRecognizer *)recognizer
{

    if([recognizer state] == UIGestureRecognizerStateBegan) {
        previousScale = 1.0;
        lastPoint = [recognizer locationInView:[recognizer view]];
    }

    if ([recognizer state] == UIGestureRecognizerStateChanged) {

        CGFloat currentScale = [[[recognizer view].layer valueForKeyPath:@"transform.scale"] floatValue];

        // Constants to adjust the max/min values of zoom
        const CGFloat kMaxScale = 4.0;
        const CGFloat kMinScale = 1.0;

        CGFloat newScale = 1 -  (previousScale - [recognizer scale]); // new scale is in the range (0-1)
        newScale = MIN(newScale, kMaxScale / currentScale);
        newScale = MAX(newScale, kMinScale / currentScale);
        scale = newScale;

        CGAffineTransform transform = CGAffineTransformScale([[recognizer view] transform], newScale, newScale);

        [recognizer view].transform = transform;

        CGPoint point = [recognizer locationInView:[recognizer view]];
        CGAffineTransform transformTranslate = CGAffineTransformTranslate([[recognizer view] transform], point.x-lastPoint.x, point.y-lastPoint.y);

        [recognizer view].transform = transformTranslate;
        NSLog(@"Transformed");
    }       
}

But I do now know how I can add the animation here. Thanks for any help!

You should be using a UIScrollView to achieve the pinch to zoom effect as UIScrollView is already integrated along with animation. Just add your UIView inside a UIScrollView.

Here is great tutorial on UIScrollView. He is using a UIImageView but UIView will behave in a similar way.

https://www.raywenderlich.com/122139/uiscrollview-tutorial

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM