调整高宽比UIImage?

我使用这段代码来调整iPhone上的图像大小:

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

只要图像的宽高比与新resize的图像的高宽比相匹配,哪个效果很好。 我想修改这个,以保持正确的长宽比,只是在图像没有出现的地方放一个黑色的背景。 所以我仍然会得到一个320×480的图像,但在顶部和底部或侧面有黑色,这取决于原始图像的大小。

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

当你设置你的屏幕矩形之后,做下面的事情来决定在哪里画图像:

 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。