我正在开发一个应用,用户点击图片并上传它们。我的应用程序中有一个按钮,单击它时,相机模式将打开。用户可以单击图像并查看预览。在预览中,图像看起来很好,占据整个屏幕。稍后我必须在宽度为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;
}
但这对我不起作用。图像仍然失真。
答案 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;