Search code examples
ipaduipinchgesturerecognizer

Zoom UIImageView from center of two fingers and also with button click


I have a image view and want to add some custom pinch gesture recognizers. I'm able to zoom my image view, but the problem is, it is not zooming in from the center of the two fingers.

How can I zoom from center of the two fingers? This is what I'm currently doing (in viewDidLoad)

UIPinchGestureRecognizer* pinchRecognizer = 
    [[UIPinchGestureRecognizer alloc] initWithTarget:self
                                              action:@selector(handlePinch:)];    
 [imageView addGestureRecognizer:pinchRecognizer]; 

here is the code for pinch method

- (IBAction)handlePinch:(UIPinchGestureRecognizer *)recognizer
{  

    recognizer.view.transform = CGAffineTransformScale(recognizer.view.transform, recognizer.scale, recognizer.scale);
    recognizer.scale = 1;

}

Thanx for the rep guys...now here i'm updating my question.. i want to zoom image on button click..What i'm doing is

-(IBAction)Zoom_image:(id)sender {

 CGFloat scaleValue = 2;

 CGAffineTransform transform = GAffineTransformMakeScale(scaleValue,scaleValue);

 self.backgroundImgView.transform = transform;

}


Solution

  • This will also work. Just move the image to the center of the pinch, scale it and then back to its position in just one transform.

    - (void) pinch:(UIPinchGestureRecognizer *) recognizer {
    
        CGPoint anchor = [recognizer locationInView:imageToScale];
        anchor = CGPointMake(anchor.x - imageToScale.bounds.size.width/2, anchor.y-imageToScale.bounds.size.height/2);
    
        CGAffineTransform affineMatrix = imageToScale.transform;
        affineMatrix = CGAffineTransformTranslate(affineMatrix, anchor.x, anchor.y);
        affineMatrix = CGAffineTransformScale(affineMatrix, [recognizer scale], [recognizer scale]);
        affineMatrix = CGAffineTransformTranslate(affineMatrix, -anchor.x, -anchor.y);
        imageToScale.transform = affineMatrix;
    
        [recognizer setScale:1];
    }