[英]Layout constraint to resize image to screen width maintaining aspect ratio
[英]Resize image maintaining aspect ratio
我正在开发一个应用程序,用户可以在其中单击图像并将其上传。 我的应用程序中有一个按钮,单击它会打开相机模式。 用户可以单击图像并查看预览。 在预览中,图像看起来不错,并且占据了整个屏幕。 稍后,我必须在宽度为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;
}
但这对我不起作用。 图像仍然失真。
您需要自己计算比例。 确定图像需要缩小多少,并将其应用于宽度和高度。
就像是
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.