使用宽高比调整UIImage的大小? [英] Resize UIImage with aspect ratio?

查看:193
本文介绍了使用宽高比调整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!

推荐答案

设置屏幕矩形后,执行以下操作以确定绘制图像的矩形: / p>

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天全站免登陆