0

我正在创建一个 iOS 应用程序,其中的图像比我的 UIImageView 大。我想缩放这些图像,使图像高度与图像视图高度相同。图像不会被剪裁在两侧,而只会被剪裁在一侧。如何缩放 UIImages?UIViewContentModeScaleAspectFit 适合最长端,因此整个图像都在屏幕上,但我希望它适合高度而不是最长端。

4

3 回答 3

2

试试这个代码,

        //find out the width and height ratio of your image.
        double ratio = [UIImage imageNamed:@"Your_image.png"].size.width / [UIImage imageNamed:@"Your_image.png"].size.height;

        //determine the calculate width according the height. here height is set as 568.
        double calculatedWidth = ratio * 568;

        float xPosition = 0.0;
        //if calculated width is greater than the screen width than we need to change the starting position which was set to 0 initially.
        if (calculatedWidth > [UIScreen mainScreen].bounds.size.width)
        {
            xPosition = (calculatedWidth - [UIScreen mainScreen].bounds.size.width) * - 1;
        }

       //initiate your image view here.
        UIImageView *yourImageView = [[UIImageView alloc] initWithFrame:CGRectMake(xPosition, 0, calculatedWidth, 568)];
        yourImageView.image = [UIImage imageNamed:@"Your_image.png"];
        [self.view addSubview:yourImageView];
于 2013-08-13T18:01:31.463 回答
1

以下是你得到你想要的东西的方法:

// Set image view to clip to bounds
self.imageView.clipToBounds = YES;
// Calculate aspect ratio of image
CGFloat ar1 = self.imageView.image.size.width / self.imageView.image.size.height;
// Calculate aspect ratio of image view
CGFloat ar2 = self.imageView.frame.size.width / self.imageView.frame.size.height;
// Set fill mode accordingly
if (ar1 > ar2) {
  self.imageView.contentMode = UIViewContentModeScaleAspectFill;
} else {
  self.imageView.contentMode = UIViewContentModeScaleAspectFit;
}
于 2013-08-13T19:35:19.407 回答
1

如果您只想使高度完全适合图像视图,则需要进行一些数学运算以找出正确的宽度比。尝试这个:

float maxHeight = 480.0f;   //this is the height of your container view.
float origHeight = imageView.frame.size.height;
float origWidth = imageView.frame.size.width;

//at this point we can create a proportion. 
//origHeight / origWidth = maxHeight / X (where X = the new width)
//divide the expression by maxHeight and you can solve for the new width: 
float newWidth = (origHeight / origWidth) / maxHeight;

至此,您拥有制作图像所需的尺寸;您总是希望高度与 maxHeight 相同,并且您已经进行了数学运算以找出当高度 = maxHeight 时与原始图像尺寸成正比的新宽度。

在 StackOverflow上查看这个关于如何调整 UIImageViews 大小的答案。将该高度和宽度传递给该答案中的函数。一切都应该很好!

于 2013-08-13T18:59:57.163 回答