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;
}