使用宽高比调整UIImage的大小?

Cor*_*eke 37 iphone core-graphics uiimage ios

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

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

只要图像的宽高比与新调整大小的图像的宽高比相匹配,哪个工作正常.我想修改它,以便保持正确的宽高比,并在图像不显示的任何地方放置黑色背景.所以我仍然会得到一张320x480的图像,但在顶部和底部或两侧都有黑色,具体取决于原始图像尺寸.

有没有一种简单的方法来做到这一点类似于我正在做的事情?谢谢!

Fra*_*itt 55

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

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);
Run Code Online (Sandbox Code Playgroud)

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

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

  • 刚刚进行了编辑以使用fmax,这已经在Apple包含的任何预编译头文件中.与MAX()的不同之处在于它将所有内容视为整数,而Core Graphics对所有坐标值本身使用`CGFloat`s(双精度).所以在Retina屏幕上你的方法可能会偏离半个点:) (2认同)