通过保持纵横比和宽度来调整 UIImage 的大小

问题描述:

我在许多帖子中看到通过保持纵横比来调整图像大小.这些函数在调整大小时使用 RECT 的固定点(宽度和高度).但是在我的项目中,我需要仅根据宽度调整视图大小,应根据纵横比自动获取高度.任何人都可以帮助我实现这一目标.

I seen in many posts for resizing the image by keeping aspect ratio. These functions uses the fixed points(Width and Height) for RECT while resizing. But in my project, I need to resize the view based on the Width alone, Height should be taken automatically based on the aspect ratio. anyone help me to achieve this.

Srikar 的方法效果很好,如果您知道新尺寸的高度.例如,如果您只知道要缩放到的宽度而不关心高度,则首先必须计算高度的比例因子.

The method of Srikar works very well, if you know both height and width of your new Size. If you for example know only the width you want to scale to and don't care about the height you first have to calculate the scale factor of the height.

+(UIImage*)imageWithImage: (UIImage*) sourceImage scaledToWidth: (float) i_width
{
    float oldWidth = sourceImage.size.width;
    float scaleFactor = i_width / oldWidth;

    float newHeight = sourceImage.size.height * scaleFactor;
    float newWidth = oldWidth * scaleFactor;

    UIGraphicsBeginImageContext(CGSizeMake(newWidth, newHeight));
    [sourceImage drawInRect:CGRectMake(0, 0, newWidth, newHeight)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();    
    UIGraphicsEndImageContext();
    return newImage;
}