-2

在我的应用程序中,我正在用相机拍照并以 320*320 显示UIView。但是由于图像分辨率超过了UIView它的样子,看起来有点挤压。有什么办法可以调整该图像的大小吗?

4

2 回答 2

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;
}
于 2012-07-03T20:02:16.367 回答
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;
}
于 2012-07-03T19:46:36.300 回答