Cocoa-touch – How to zoom in/out an UIImage object when user pinches screen

cocoa-touchuiimageuiimagejpegrepresentation

I would like to zoom in/out an UIImage object when the user performs the standard pinch action on my application. I'm currently using a UIImageView to display my image, if that detail helps in any way.

I'm trying to figure out how to do this, but no such luck so far.

Any clues?

Best Answer

As others described, the easiest solution is to put your UIImageView into a UIScrollView. I did this in the Interface Builder .xib file.

In viewDidLoad, set the following variables. Set your controller to be a UIScrollViewDelegate.

- (void)viewDidLoad {
    [super viewDidLoad];
    self.scrollView.minimumZoomScale = 0.5;
    self.scrollView.maximumZoomScale = 6.0;
    self.scrollView.contentSize = self.imageView.frame.size;
    self.scrollView.delegate = self;
}

You are required to implement the following method to return the imageView you want to zoom.

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return self.imageView;
}

In versions prior to iOS9, you may also need to add this empty delegate method:

- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale
{
}

The Apple Documentation does a good job of describing how to do this:

Related Topic