使用原始比例调整UIImage的大小

时间:2012-02-13 14:24:13

标签: objective-c ios xcode

我正在尝试调整最大1000px宽度的图像,但原始图像分辨率的“比率”需要保持不变。即1000x1300或1000x1600等

我需要对下面的代码进行哪些更改?

- (void)setImageAndConvertToThumb:(UIImage *)image {
//image
UIImage *sizedImg = [image scaleWithMaxSize:CGSizeMake(1000, 1000) quality:kCGInterpolationHigh];
NSData *data = UIImagePNGRepresentation(sizedImg);
self.image = data;

}

1 个答案:

答案 0 :(得分:0)

宽高比只是宽度除以高度(反之亦然),所以只需使用与原始图像相同的比例计算新高度,如下所示:

- (void)setImageAndConvertToThumb:(UIImage *)image {
    //image
    CGFloat newWidth = 1000;
    CGFloat newHeight = newWidth * image.size.height / image.size.width;
    UIImage *sizedImg = [image scaleWithMaxSize:CGSizeMake(newWidth, newHeight) quality:kCGInterpolationHigh];
    NSData *data = UIImagePNGRepresentation(sizedImg);
    self.image = data;
}