Wednesday, June 5, 2013

UIScrollView zoomToRect animated example in Objective C (iOS).

UIScrollView zoomToRect animated

Zooms to a specific area of the content so that it is visible in the receiver.

- (void)zoomToRect:(CGRect)rect animated:(BOOL)animated

A rectangle defining an area of the content view.
YES if the scrolling should be animated, NO if it should be immediate.

Discussion of [UIScrollView zoomToRect animated]
This method zooms so that the content view becomes the area defined by rect, adjusting the zoomScale as necessary.

UIScrollView zoomToRect animated example.
- (void)handleDoubleTap:(UIGestureRecognizer *)gestureRecognizer {
    // double tap zooms in
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(handleSingleTap:) object:nil];
    float newScale = [imageScrollView zoomScale] * 1.5;
    // Note we need to get location of the tap in the imageView coords, not the imageScrollView
    CGRect zoomRect = [self zoomRectForScale:newScale withCenter:[gestureRecognizer locationInView:imageView]];
    [imageScrollView zoomToRect:zoomRect animated:YES];

Example of [UIScrollView zoomToRect animated].
float zoomBefore = myScrollView.zoomScale;
[myScrollView zoomToRect:zoomToRect animated:YES];
float zoomAfter = myScrollView.zoomScale;
if (zoomBefore == zoomAfter)
    [myScrollView setContentOffset:imageCoords animated:YES];

UIScrollView zoomToRect animated example.
The zoomToRect method also has the argument 'animated', ie:

[self.scrollview zoomToRect:CGRectMake(0, 0, 1, IMAGE_HEIGHT) animated:NO];
So that might be causing the problem. If not, you could try this:

CGFloat scale1 = IMAGE_WIDTH / self.scrollview.frame.size.width;
CGFloat scale2 = IMAGE_HEIGHT / self.scrollview.frame.size.height;
[self.scrollview setZoomScale:MAX(scale1, scale2) animated:NO];
[self.scrollView scrollRectToVisible:CGRectMake(0,0,0,0) animated:NO];

End of UIScrollView zoomToRect animated example article.