ios 如何在保持纵横比的同时调整 UIImage 的大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6703502/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 20:47:02  来源:igfitidea点击:

How to resize an UIImage while maintaining its Aspect Ratio

iosobjective-cuiimageuikit

提问by Rahul

I want to resize a UIImagewith maintaining its Aspect Ratio. I have written the following code, but it is not working as expected.

我想调整 a 的大小UIImage并保持其纵横比。我已经编写了以下代码,但它没有按预期工作。

Code

代码

-(UIImage * ) scaleImage: (UIImage * ) image toSize: (CGSize) targetSize {

    CGFloat scaleFactor = 1.0;
    if (image.size.width > targetSize.width || image.size.height > targetSize.height)
        if (!((scaleFactor = (targetSize.width / image.size.width)) > (targetSize.height / image.size.height))) //scale to fit width, or
            scaleFactor = targetSize.height / image.size.height; // scale to fit heigth.
    UIGraphicsBeginImageContext(targetSize);
    CGRect rect = CGRectMake((targetSize.width - image.size.width * scaleFactor) / 2, (targetSize.height - image.size.height * scaleFactor) / 2,
        image.size.width * scaleFactor, image.size.height * scaleFactor);
    [image drawInRect: rect];
    UIImage * scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}

What exactly is wrong here?

这里究竟有什么问题?

回答by zpasternack

I'm using something similar to this in a few projects:

我在几个项目中使用了类似的东西:

- (UIImage*) scaleImage:(UIImage*)image toSize:(CGSize)newSize {
    CGSize scaledSize = newSize;
    float scaleFactor = 1.0;
    if( image.size.width > image.size.height ) {
        scaleFactor = image.size.width / image.size.height;
        scaledSize.width = newSize.width;
        scaledSize.height = newSize.height / scaleFactor;
    }
    else {
        scaleFactor = image.size.height / image.size.width;
        scaledSize.height = newSize.height;
        scaledSize.width = newSize.width / scaleFactor;
    }

    UIGraphicsBeginImageContextWithOptions( scaledSize, NO, 0.0 );
    CGRect scaledImageRect = CGRectMake( 0.0, 0.0, scaledSize.width, scaledSize.height );
    [image drawInRect:scaledImageRect];
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();    

    return scaledImage;
}

回答by Dan J

If this is for displaying in a UI, you can use Interface Builder and specify the "Aspect Fit" property.

如果这是为了在 UI 中显示,您可以使用 Interface Builder 并指定“Aspect Fit”属性。

You can also do this in code by setting the content mode to UIViewContentModeScaleAspectFit:

您还可以通过将内容模式设置为在代码中执行此操作UIViewContentModeScaleAspectFit

imageView.contentMode = UIViewContentModeScaleAspectFit;

回答by Rahul

This method takes an image and a max dimension. If the max original image dimension is less than the specified max dimension, you get the original back so it won't get blown up. Otherwise, you get a new image having a max dimension of the one specified and the other determined by the original aspect ratio. So as an example, if you give it a 1024x768 image and max dimension of 640 you get back a 640x480 version, if you give it a 768x1024 image and max dimension of 640 you get back a 480x640 version.

此方法采用图像和最大尺寸。如果最大原始图像尺寸小于指定的最大尺寸,您将获得原始图像,这样它就不会被炸毁。否则,您将获得一个新图像,其最大尺寸为指定的一个,另一个由原始纵横比确定。举个例子,如果你给它一个 1024x768 的图像和 640 的最大尺寸,你会得到一个 640x480 的版本,如果你给它一个 768x1024 的图像和 640 的最大尺寸,你会得到一个 480x640 的版本。

- (UIImage *)resizeImage:(UIImage *)image
        withMaxDimension:(CGFloat)maxDimension
{
    if (fmax(image.size.width, image.size.height) <= maxDimension) {
        return image;
    }

    CGFloat aspect = image.size.width / image.size.height;
    CGSize newSize;

    if (image.size.width > image.size.height) {
        newSize = CGSizeMake(maxDimension, maxDimension / aspect);
    } else {
        newSize = CGSizeMake(maxDimension * aspect, maxDimension);
    }

    UIGraphicsBeginImageContextWithOptions(newSize, NO, 1.0);
    CGRect newImageRect = CGRectMake(0.0, 0.0, newSize.width, newSize.height);
    [image drawInRect:newImageRect];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return newImage;
}

回答by Julian Król

In my case (I wanted to have an image in a UIView) and keep the ratio with auto layout the way described herewas great. The most important part of the article for me was (almost quoting):

在我的情况下(我想在 UIView 中有一个图像)并保持自动布局的比例,这里描述的方式很棒。对我来说,这篇文章最重要的部分是(几乎引用):

constraint = [NSLayoutConstraint constraintWithItem:self.imageView
                                          attribute:NSLayoutAttributeHeight
                                          relatedBy:NSLayoutRelationEqual
                                             toItem:self.imageView 
                                          attribute:NSLayoutAttributeWidth 
                                         multiplier:ration 
                                           constant:0.0f];

[self.imageView addConstraint:constraint];

the only thing is to calculate the ratio according to the actual width and height of image. I found this way easy and elegant.

唯一的事情就是根据图像的实际宽度和高度计算比例。我发现这种方式既简单又优雅。

回答by channi

- (UIImage *)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize {
    UIGraphicsBeginImageContext(newSize);
    float ratio = newSize.width/image.size.width;
    [image drawInRect:CGRectMake(0, 0, newSize.width, ratio * image.size.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    NSLog(@"New Image Size : (%f, %f)", newImage.size.width, newImage.size.height);
    UIGraphicsEndImageContext();
    return newImage;
}