5
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

UIScrollView zoom by tap

Last updated at Posted at 2012-10-04
tapToZoom.m

# define DEFAULT_ZOOM_SCALE 5.0
# define SCALE_RATE 2.0

- (IBAction)onDoubleTapOnMap:(UITapGestureRecognizer *)sender {
    
    float zoom = self.scrollView.zoom;
    
    CGPoint tapPoint = [sender locationInView:self.scrollView];

    // Zoom=self.scrollView.zoom → Zoom=1.0 
    tapPoint.x /= zoom;
    tapPoint.y /= zoom;

    if (zoom >= self.scrollView.maximumZoomScale) {
        // already max zoom : set zoom to default
        [self.scrollView setZoomScale:DEFAULT_ZOOM_SCALE animated:YES];
    } else {
        // zoom up

        float newZoom = zoom * SCALE_RATE;
        if (newZoom >= self.scrollView.maximumZoomScale) {
            newZoom = self.scrollView.maximumZoomScale;
        }

        CGRect newRect = [self zoomRectForScrollView:self.scrollView withScale:newZoom withCenter:tapPoint];
        [self.scrollView zoomToRect:newRect animated:YES];
    }
}

// http://developer.apple.com/library/ios/#documentation/WindowsViews/Conceptual/UIScrollView_pg/ZoomZoom/ZoomZoom.html#//apple_ref/doc/uid/TP40008179-CH102-SW7
- (CGRect)zoomRectForScrollView:(UIView *)scrollView withScale:(float)scale withCenter:(CGPoint)center {
    
    CGRect zoomRect;
    
    // The zoom rect is in the content view's coordinates.
    // At a zoom scale of 1.0, it would be the size of the
    // imageScrollView's bounds.
    // As the zoom scale decreases, so more content is visible,
    // the size of the rect grows.
    zoomRect.size.height = scrollView.frame.size.height / scale;
    zoomRect.size.width  = scrollView.frame.size.width  / scale;
    
    // choose an origin so as to get the right center.
    zoomRect.origin.x = center.x - (zoomRect.size.width  / 2.0);
    zoomRect.origin.y = center.y - (zoomRect.size.height / 2.0);
    
    return zoomRect;
}
5
6
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?