如何将UIImage调整为特定大小

时间:2012-07-03 19:41:25

标签: ios uiview uiimage image-resizing

在我的应用中,我正在用相机拍照并以320 * 320 UIView显示。但由于图像分辨率高于UIView,因此它的外观受到挤压。有什么方法可以调整图像大小吗?

2 个答案:

答案 0 :(得分:3)

以下是如何在保留纵横比的同时调整图像大小。以下代码来自UIImage的类别:

+ (UIImage*)imageWithImage:(UIImage *)image 
              scaledToSize:(CGSize)newSize
{

    float heightToWidthRatio = image.size.height / image.size.width;
    float scaleFactor = 1;
    if(heightToWidthRatio > 0) {
        scaleFactor = newSize.height / image.size.height;
    } else {
        scaleFactor = newSize.width / image.size.width;
    }

    CGSize newSize2 = newSize;
    newSize2.width = image.size.width * scaleFactor;
    newSize2.height = image.size.height * scaleFactor;

    UIGraphicsBeginImageContext(newSize2);
    [image drawInRect:CGRectMake(0,0,newSize2.width,newSize2.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return newImage;
}

答案 1 :(得分:0)

我这样做,但首先我将照片选择器设置为可编辑,因此它是默认的1:1宽高比,如下所示:

imgPicker.allowsImageEditing = YES; //I think this is what you're really looking for

然后我使用这种方法调整图像大小:

-(UIImage*)resizeImage:(UIImage*)image{
    CGSize newSize = CGSizeMake(480.0, 480.0);
    UIGraphicsBeginImageContext(newSize);
        [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
        UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}