开发者

Formula for producing a CGRect for a UIScrollView, that displays a UIImage in scaled to fit way

开发者 https://www.devze.com 2023-01-01 21:30 出处:网络
I am loading in images with varying sizes and putting them in UIScrollViews, all the images are larger than the UIScrollView.

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 im开发者_运维问答age 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


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号