views:

209

answers:

1

Hi

I am loading in images with varying sizes and putting them in UIScrollViews, all the images are larger than the UIScrollView. The user can scroll and zoom as they please, but initially I would like for the image to be centered and scaled so the largest side of the image aligns with the edge of the scrollView, i.e. if the picture is in landscape I would like to size and scale it so that the left and right side goes all the way to the edge of the UIScrollVIew and vice versa

I found a formula in a utility function in the Programming guide but it does not quite fit my needs.

My approach is to use:

CGrect initialPos = ?
[self.scrollView zoomToRect:initialPos animated:YES];

I know the size of my scrollView and the size of my image, what I need to figure out is the scale and CGRect to apply to the scrollView to center and size my image.

Hope someone can help out:) Thanks

+1  A: 

Edit: previous version was sizing the image to the view rather than the other way around. I think this should correct that:

double imgRatio = imageSize.width / imageSize.height;
double viewRatio = viewSize.width / viewSize.height;

if ( imgRatio >= viewRatio )
{
    initialPos.size.width = imageSize.width;
    initialPos.size.height = imageSize.width / viewRatio;
    initialPos.origin.x = 0;
    initialPos.origin.y = (imageSize.height - initialPos.size.height) / 2;
}
else
{
    initialPos.size.height = imageSize.height;
    initialPos.size.width = imageSize.height * viewRatio;
    initialPos.origin.y = 0;
    initialPos.origin.x = (imageSize.width - initialPos.size.width) / 2;
}
walkytalky
Hi Walkytalky and thanks:)I understand what you are doing, but does this take into account the scaling? This positions the image correctly in the scroll view but does not change the scale so that the image fits inside the scroll view.
RickiG
Doh. Sorry, I answered the question back to front -- sizing the image to the view rather than the view's zoom to the image. Will update.
walkytalky
Hi Walkytalky, all is forgiven:) it works perfectly on both landscape and portrait images.To others passing by: the viewRatio in my instance is the UIScrollView width/heigh.Once the scaling is done I use:[self.scrollView zoomToRect:initialPos animated:YES]; to animate it to the right scale.Thanks again.
RickiG