[英]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.