使用适当的宽高比调整图像大小

时间:2012-03-05 13:41:47

标签: iphone ipad

我正在开发新的应用程序,其中,我有不同大小的图像。我已尝试多次使用不同的解决方案,但无法找到适合图像的宽高比。我也希望以高质量显示图像。有些图像的分辨率为20 * 20到3456 * 4608,或者它可能会很高。

所有图片都会在没有裁剪的情况下显示,但我们的应用程序屏幕尺寸为300 * 370像素。

我遵循以下参考资料:

1:Resize UIImage with aspect ratio?

2:UIViewContentModeScaleAspectFit

3:scale Image in an UIButton to AspectFit?

4:Resize UIImage with aspect ratio?

2 个答案:

答案 0 :(得分:0)

我用来将图像调整到最大边缘1000px的代码是:

const int maxPhotoWidthOrHeight = 1000;

- (UIImage*)resizeImageWithImage:(UIImage*)image
{
    CGFloat oldWidth = image.size.width;
    CGFloat oldHeight = image.size.height;
    NSLog(@"Old width %f , Old Height : %f ",oldWidth,oldHeight);

    if (oldHeight > maxPhotoWidthOrHeight || oldWidth > maxPhotoWidthOrHeight) {//resize if necessary
        CGFloat newHeight;
        CGFloat newWidth;
        if (oldHeight > oldWidth ) {
            newHeight = maxPhotoWidthOrHeight;
            newWidth = oldWidth * (newHeight/oldHeight);
        }
        else{
            newWidth = maxPhotoWidthOrHeight;
            newHeight = oldHeight * (newWidth/oldWidth);
        }
        CGSize newSize = CGSizeMake(newWidth, newHeight);
        UIGraphicsBeginImageContext( newSize );
        [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
        UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        NSLog(@"New width %f , New Height : %f ",newImage.size.width,newImage.size.height);

        return newImage;
    }
    else{//do not resize because both edges are less than 1000px
        return image;
    }

}

答案 1 :(得分:0)

- 请添加代码示例,否则很难解决您的问题。

此处找到的解决方案也是How to scale a UIImageView proportionally?

imageView.contentMode = UIViewContentModeScaleAspectFit;