1
votes

I am fairly new to this and I'm trying to use pinch gestures to zoom in on a UIImage and be able to zoom into any specific part of the image. However, when I zoom it only zooms from the upper left corner of the UIView. So I only get to see the upper left corner of the image zoomed in. I'd like to be able to zoom/pan the image similar to how the Photos app works. Here is my code so far:

In ViewDidLoad:

...
 // Load the image to be viewed into the UIImage
self.theImage.image = self.theNewImage;

UIPinchGestureRecognizer *pinchGestRecog = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(twoFingerPinch:)];

// ADD GESTURE RECOGNIZER TO THE VIEW
[theImage addGestureRecognizer:pinchGestRecog];

// ALLOW USER INTERACTION ON THE VIEW
[theImage setUserInteractionEnabled:YES];

// SET IMAGE ZOOM SCALE LIMITS
imageCurrentScale = 1.0;
imageMaxScale = 2.0;
imageMinScale = 0.5;

And then in my twoFingerPinch method:

 - (void)twoFingerPinch:(UIPinchGestureRecognizer *)aPinchGesture
{
if (imageCurrentScale * [aPinchGesture scale] > imageMinScale && imageCurrentScale * [aPinchGesture scale] < imageMaxScale) {

    imageCurrentScale = imageCurrentScale * [aPinchGesture scale];
    CGAffineTransform zoomTransform = CGAffineTransformMakeScale(imageCurrentScale, imageCurrentScale);
    [[aPinchGesture view] setTransform:zoomTransform];
}
[aPinchGesture setScale:1.0];

}

Is panning somehow the answer? I'm not really sure how panning works. Any suggestions? Thanks.

1

1 Answers

0
votes

The reason why you zoom to your upper left corner is because the center of your scale transformation is the UIView.layer.anchorPoint which is default the upper left corner (0,0). If you want to zoom correctly you somehow have to figure out the center of your pinch gesture and then set your anchorPoint to that position.

But you shouldn't do that anyway. The recommended way to zoom into a UIImageView is to place the the image view into a UIScrollView and set the contentSize and maximumZoomScale and minimumZoomScale values accordingly. Set yourself as the delegate of your UIScrollView and return the UIImageView in the viewForZooming delegate method.

The scrollview will handle the pinching and zooming for you.