简体   繁体   English

如何相对于原始图像尺寸比例设置UIimageview宽度

[英]how to set UIimageview width with respect to the original image size ratio

In my iphone app i need to set image in the image view. 在我的iPhone应用程序中,我需要在图像视图中设置图像。

the image view height is always 100pixels. 图像视图高度始终为100像素。

we need to set the width of the image view with respect to the original image scale ratio.

ie per suppose width X height of an image is 300x400 (original) (4x3) 也就是说,假设每个图像的宽度X高度为300x400(原始)(4x3)

our displayed image view image size would be 75X100 我们显示的图像视图的图像大小将为75X100

width X height of an image is 512x512 (original) (1x1) 图片的宽度X高度为512x512(原始)(1x1)

our displayed image view image size would be 100X100 我们显示的图像视图的图像大小将为100X100

width X height of an image is 128 x 256 (original) (1x2) 图片的宽度X高度为128 x 256(原始)(1x2)

our displayed image view image size would be 50X100 我们显示的图像视图的图像大小将为50X100

in all those cases image view height 100pixel should be same, but the width need to varie with respect to the image ratio.

And finally the image view should be in center of the view 最后,图像视图应位于视图中心

How to achieve it 如何实现

There are a couple of ways you can achieve this. 有两种方法可以实现此目的。 The simplest is to set the scaling mode on the image view to Aspect Fill in Interface Builder, or 最简单的方法是在Interface Builder中将图像视图上的缩放模式设置为Aspect Fill,或者

imageView.contentMode = UIViewContentModeScaleAspectFit;

The second way is to calculate the aspect ratio of the image and set the width. 第二种方法是计算图像的纵横比并设置宽度。 Something like: 就像是:

UIImage *myImage = [UIImage imageNamed:@"MyImage"];
float aspectRatio = myImage.size.width / myImage.size.height;
float viewWidth = 100 * aspectRatio;

Well Its up to your logics. 好吧,这取决于您的逻辑。
You can get UIImage height and width. 您可以获取UIImage高度和宽度。

 UIImage *image = [UIImage imageNamed:@"anyImage.png"];
 float imageHeight = image.size.height;
 float imageWidth = image.size.width;

After that you can calculate imageViewWidth-. 之后,您可以计算imageViewWidth-。
According to your requirement - 根据您的要求-

float value = imageHeight/100.0;
float iV_Width = imageWidth/value;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM