用纵横比调整 UIImage 的大小? [英] Resize UIImage with aspect ratio?

查看:35
本文介绍了用纵横比调整 UIImage 的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此代码在 iPhone 上调整图像大小:

I'm using this code to resize an image on the iPhone:

CGRect screenRect = CGRectMake(0, 0, 320.0, 480.0);
UIGraphicsBeginImageContext(screenRect.size);
[value drawInRect:screenRect blendMode:kCGBlendModePlusDarker alpha:1];
UIImage *tmpValue = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

只要图像的纵横比与调整后的新图像的纵横比相匹配,这效果很好.我想修改它以保持正确的纵横比,并在图像未显示的任何地方放置黑色背景.所以我仍然会得到一个 320x480 的图像,但顶部和底部或侧面是黑色的,这取决于原始图像的大小.

Which is working great, as long as the aspect ratio of the image matches that of the new resized image. I'd like to modify this so that it keeps the correct aspect ratio and just puts a black background anywhere the image doesn't show up. So I would still end up with a 320x480 image but with black on the top and bottom or sides, depending on the original image size.

是否有一种类似于我正在做的事情的简单方法?谢谢!

Is there an easy way to do this similar to what I'm doing? Thanks!

推荐答案

设置屏幕矩形后,请执行以下类似操作来决定在哪个矩形中绘制图像:

After you set your screen rect, do something like the following to decide what rect to draw the image in:

float hfactor = value.bounds.size.width / screenRect.size.width;
float vfactor = value.bounds.size.height / screenRect.size.height;

float factor = fmax(hfactor, vfactor);

// Divide the size by the greater of the vertical or horizontal shrinkage factor
float newWidth = value.bounds.size.width / factor;
float newHeight = value.bounds.size.height / factor;

// Then figure out if you need to offset it to center vertically or horizontally
float leftOffset = (screenRect.size.width - newWidth) / 2;
float topOffset = (screenRect.size.height - newHeight) / 2;

CGRect newRect = CGRectMake(leftOffset, topOffset, newWidth, newHeight);

如果您不想放大小于 screenRect 的图像,请确保 factor 大于或等于 1(例如 factor = fmax(factor, 1)).

If you don't want to enlarge images smaller than the screenRect, make sure factor is greater than or equal to one (e.g. factor = fmax(factor, 1)).

要获得黑色背景,您可能只想将上下文颜色设置为黑色并在绘制图像之前调用 fillRect.

To get the black background, you would probably just want to set the context color to black and call fillRect before drawing the image.

这篇关于用纵横比调整 UIImage 的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆