OWolf
OWolf

Reputation: 5132

gesture recognizer, strange behavior (Multiplier effect) iOS

I am trying to add gesture recognizers to a view. When I add both pan (for move) and pinch (for scale), I get some strange behavior.

After the view (which happens to contain an imageView) is scaled the pan gesture recognizer seems to multiply the effect of the move. Or it still assumes the original scale so the move is faster than it should be?

Here is the code for the methods to move and scale:

//ivars for gesture recognizers/transforms
CGFloat scale;
CGFloat rotation;
CGPoint translatedPoint;
CGFloat _lastScale;
CGFloat _lastRotation;  
CGFloat _firstX;
CGFloat _firstY;

-(void)scale:(id)sender {
    if([(UIPinchGestureRecognizer*)sender state] == UIGestureRecognizerStateBegan) {
        _lastScale = 1.0;
    }
    scale = 1.0 - (_lastScale - [(UIPinchGestureRecognizer*)sender scale]);
    CGAffineTransform currentTransform = gestureView.transform;
    CGAffineTransform newTransform = CGAffineTransformScale(currentTransform, scale, scale);
    [gestureView setTransform:newTransform];
    _lastScale = [(UIPinchGestureRecognizer*)sender scale];
    NSLog(@"gestureView origin x: %f, y: %f", gestureView.frame.origin.x, gestureView.frame.origin.y);
    NSLog(@"gestureView center x: %f, y: %f",[gestureView center].x, [gestureView center].y);
    NSLog(@"gestureView scale x: %f, scale y: %f", gestureView.frame.size.width, gestureView.frame.size.height);

}

-(void)move:(id)sender {
    translatedPoint = [(UIPanGestureRecognizer*)sender translationInView:gestureView];
    if([(UIPanGestureRecognizer*)sender state] == UIGestureRecognizerStateBegan) {
        _firstX = [gestureView center].x;
        _firstY = [gestureView center].y;
    }
    translatedPoint = CGPointMake(_firstX+translatedPoint.x, _firstY+translatedPoint.y);
    [gestureView setCenter:translatedPoint];
    NSLog(@"gestureView origin x: %f, y: %f", gestureView.frame.origin.x, gestureView.frame.origin.y);
    NSLog(@"gestureView center x: %f, y: %f",[gestureView center].x, [gestureView center].y);
}

Here is the project: owolf.net/uploads/StackOverflow/GestureRecognizerTest.zip

Thanks for reading!

Upvotes: 0

Views: 414

Answers (1)

Kalle
Kalle

Reputation: 13346

You're asking for translation inside the gestureView, which will give you the scaled translation. If the gestureView was scaled down to 50%, a 10 pixel move along x-axis would give x=20 in the translatedPoint value, because 10 pixels "on the outside" doubles on the scaled down ("higher resolution") gestureView.

You then apply that to the gestureView's frame (center is simply a convenience method which sets the frame to center.x - frame.size.width/2, center.y - frame.size.height/2, frame.size) which means it's affected by the scale.

What you probably want to do is change the translationInView: call to look in gestureView.superview, not in gestureView itself.

Upvotes: 1

Related Questions