调整图像维护宽高比

时间:2013-06-28 15:51:20

标签: ios objective-c uiimageview aspect-ratio resize-image

我正在开发一个应用,用户点击图片并上传它们。我的应用程序中有一个按钮,单击它时,相机模式将打开。用户可以单击图像并查看预览。在预览中,图像看起来很好,占据整个屏幕。稍后我必须在宽度为110和高度为111的UIImageView中显示此图像。当我在此显示时,图像会变形并在边缘处被裁剪。我的主要目标是保持宽高比。

我试过这样做。

- (void)displayCapturedImage
{
//[self.imageView setImage:self.capturedImage];
    CGSize smallSize = CGSizeMake(110, 111);
    [self.imageView setImage:[self imageWithImage:self.capturedImage scaledToSize:smallSize]];

}

- (UIImage*)imageWithImage:(UIImage*)image
          scaledToSize:(CGSize)newSize;
{
    UIGraphicsBeginImageContext( newSize );
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return newImage;
}

但这对我不起作用。图像仍然失真。

1 个答案:

答案 0 :(得分:1)

您需要自己计算比例。确定图像需要的尺寸,并将其应用于宽度和高度。

这样的东西
float widthFactor  = targetWidth / width;
            float heightFactor = targetHeight / height;

            if ( widthFactor < heightFactor )
                scaleFactor = widthFactor;
            else
                scaleFactor = heightFactor;

            scaledWidth  = width  * scaleFactor;
            scaledHeight = height * scaleFactor;

            if ( widthFactor < heightFactor )
                thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;

            else if ( widthFactor > heightFactor )
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;