可能重复:
使用宽高比调整UIImage的大小?
下面这段代码正在完美地调整图像大小,但问题是它会混淆纵横比(导致图像偏斜).有什么指针吗?
// Change image resolution (auto-resize to fit)
+ (UIImage *)scaleImage:(UIImage*)image toResolution:(int)resolution {
CGImageRef imgRef = [image CGImage];
CGFloat width = CGImageGetWidth(imgRef);
CGFloat height = CGImageGetHeight(imgRef);
CGRect bounds = CGRectMake(0, 0, width, height);
//if already at the minimum resolution, return the orginal image, otherwise scale
if (width <= resolution && height <= resolution) {
return image;
} else {
CGFloat ratio = width/height;
if (ratio > 1) {
bounds.size.width = resolution;
bounds.size.height = bounds.size.width / ratio;
} else …
Run Code Online (Sandbox Code Playgroud) 我正在使用此代码调整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的图像,但在顶部和底部或两侧都有黑色,具体取决于原始图像尺寸.
有没有一种简单的方法来做到这一点类似于我正在做的事情?谢谢!