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

标签 ios iphone uiimage core-graphics

我正在使用这段代码在 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/

相关文章:

ios - KVO 不工作(观察另一个类的属性)

ios - 在锁屏iOS7上显示音乐播放控件的最佳方法

ios - iOS 上的标准位置服务耗电

iphone - 在 uiimageview 中加载大图像时的内存消耗

ios - 扫描仪 View 中的导航栏 - IOS - Swift

ios - 滚动时 UISwitch 正在更改其他单元格上的状态

ios - CLLocationManager 无法识别

ios - 如何知道collectionview单元在设备屏幕上的位置

ios - 如何设置要放入 tableView 单元格中的 UIImage 的大小

ios - 错误域=com.flickr 代码=108 "The operation couldn’ t 完成