user1573607
user1573607

Reputation: 522

iOS - Zooming UIImageView on a UIScrollView

I'm making a picture gallery, with an amount of UIImageView inside UIScrollViews, inside a main UIScrollView. The gallery allows to change horizontally the pictures, and doing zoom on each one.

It works fine in general, but the animation of zooming is not working good at all.

The problem appears when the image is small and not filling all the screen. When you make bigger the image, but not until filling the full gallery, the image suffers a little displacement, that I correct with the next code, to get it in the center of the ScrollView.

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

    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];
    aImg.frame = [self centeredFrameForScrollView:myScrollView andUIView:aImg];
    [UIView commitAnimations];
}

At last the image is in the correct place, but it seems a little bit weird. What should I do?

Upvotes: 1

Views: 4130

Answers (2)

Bhavin
Bhavin

Reputation: 27225

Sample Code :

- (void)handleTwoFingerTap:(UIGestureRecognizer *)gestureRecognizer
{
    // two-finger tap zooms out
    float newScale = [scrlView zoomScale] / ZOOM_STEP;
    CGRect zoomRect = [self zoomRectForScale:newScale withCenter:[gestureRecognizer locationInView:gestureRecognizer.view]];
    [scrlView zoomToRect:zoomRect animated:YES];
}

- (CGRect)zoomRectForScale:(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 = [scrlView frame].size.height / scale;
    zoomRect.size.width  = [scrlView frame].size.width  / scale;
    // choose an origin so as to get the right center.
    zoomRect.origin.x    = scrlView.center.x - (zoomRect.size.width  / 2.0);
    zoomRect.origin.y    = scrlView.center.y - (zoomRect.size.height / 2.0);
    return zoomRect;
}

Upvotes: 1

user431791
user431791

Reputation: 341

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

Upvotes: 1

Related Questions