UIPinchGestureRecognizer position the pinched view between the two fingers

前端 未结 2 994
时光取名叫无心
时光取名叫无心 2020-12-02 07:34

I successfully implemented a pinch a zoom of a view. However, the view doesn\'t position itself where I wished it to be. For the stackoverflowers with an iPad, I would like

2条回答
  •  青春惊慌失措
    2020-12-02 07:50

    You can get the CGPoint of the midpoint between two fingers via the following code in the method handlingPinchGesture.

    CGPoint point = [sender locationInView:self];
    

    My whole handlePinchGesture method is below.

    /*
    instance variables
    
    CGFloat lastScale;
    CGPoint lastPoint;
    */
    
    - (void)handlePinchGesture:(UIPinchGestureRecognizer *)sender {
        if ([sender numberOfTouches] < 2)
            return;
    
        if (sender.state == UIGestureRecognizerStateBegan) {
            lastScale = 1.0;
            lastPoint = [sender locationInView:self];
        }
    
        // Scale
        CGFloat scale = 1.0 - (lastScale - sender.scale);
        [self.layer setAffineTransform:
            CGAffineTransformScale([self.layer affineTransform], 
                                   scale, 
                                   scale)];
        lastScale = sender.scale;
    
        // Translate
        CGPoint point = [sender locationInView:self];
        [self.layer setAffineTransform:
            CGAffineTransformTranslate([self.layer affineTransform], 
                                       point.x - lastPoint.x, 
                                       point.y - lastPoint.y)];
        lastPoint = [sender locationInView:self];
    }
    

提交回复
热议问题