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