7
votes

I have a UIScrollView with zooming and panning. I want the image to scroll to the center after a user command. My problem is in calculating the size and location of a frame that is in the center of the image.

Does anyone know how to calculate the correct frame for the center of my image? The problem is that if the zoomScale is different the frame changes.

Thanks!

4

4 Answers

17
votes

Here's maybe a bit better code in case anyone is in need ;-)

UIScrollView+CenteredScroll.h:

@interface UIScrollView (CenteredScroll)

-(void)scrollRectToVisibleCenteredOn:(CGRect)visibleRect
                            animated:(BOOL)animated;

@end

UIScrollView+CenteredScroll.m:

@implementation UIScrollView (CenteredScroll)

-(void)scrollRectToVisibleCenteredOn:(CGRect)visibleRect
                            animated:(BOOL)animated
{
  CGRect centeredRect = CGRectMake(visibleRect.origin.x + visibleRect.size.width/2.0 - self.frame.size.width/2.0,
                                   visibleRect.origin.y + visibleRect.size.height/2.0 - self.frame.size.height/2.0,
                                   self.frame.size.width,
                                   self.frame.size.height);
  [self scrollRectToVisible:centeredRect
                   animated:animated];
}

@end
7
votes

Based on Daniel Bauke answer, I updated his code to include zoom scale :

@implementation UIScrollView (jsCenteredScroll)

-(void)jsScrollRectToVisibleCenteredOn:(CGRect)visibleRect
                            animated:(BOOL)animated
{

    CGPoint center = visibleRect.origin;
    center.x += visibleRect.size.width/2;
    center.y += visibleRect.size.height/2;

    center.x *= self.zoomScale;
    center.y *= self.zoomScale;


    CGRect centeredRect = CGRectMake(center.x - self.frame.size.width/2.0,
                                     center.y - self.frame.size.height/2.0,
                                     self.frame.size.width,
                                     self.frame.size.height);
    [self scrollRectToVisible:centeredRect
                     animated:animated];
}

@end
2
votes
private func centerScrollContent() {
    let x = (imageView.image!.size.width * scrollView.zoomScale / 2) - ((scrollView.bounds.width) / 2)
    let y = (imageView.image!.size.height * scrollView.zoomScale / 2) - ((scrollView.bounds.height) / 2)
    scrollView.contentOffset = CGPointMake(x, y)
}
-5
votes

Okay, got it working. Here's the code incase anyone is in need:

CGFloat tempy = imageView.frame.size.height;
CGFloat tempx = imageView.frame.size.width;
CGRect zoomRect = CGRectMake((tempx/2)-160, (tempy/2)-240, myScrollView.frame.size.width, myScrollView.frame.size.height);
[myScrollView scrollRectToVisible:zoomRect animated:YES];