我正在使用这段代码在 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 的图像,但顶部和底部或侧面为黑色,具体取决于原始图像尺寸。
是否有一种类似于我正在做的简单方法来做到这一点?谢谢!
最佳答案
设置屏幕矩形后,执行类似以下的操作来决定在哪个矩形中绘制图像:
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)
).
要获得黑色背景,您可能只想将上下文颜色设置为黑色并在绘制图像之前调用 fillRect。
关于ios - 使用宽高比调整 UIImage 的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1703100/