ios 调整 UIImage 大小的最简单方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2658738/
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 17:09:11  来源:igfitidea点击:

The simplest way to resize an UIImage?

iosuiimageresize

提问by pimpampoum

In my iPhone app, I take a picture with the camera, then I want to resize it to 290*390 pixels. I was using this method to resize the image :

在我的 iPhone 应用程序中,我用相机拍照,然后我想将其调整为 290*390 像素。我正在使用这种方法来调整图像大小:

UIImage *newImage = [image _imageScaledToSize:CGSizeMake(290, 390)
                         interpolationQuality:1];    

It works perfectly, but it's an undocumented function, so I can't use it anymore with iPhone OS4.

它运行良好,但它是一个未记录的功能,所以我不能再在 iPhone OS4 上使用它。

So... what is the simplest way to resize an UIImage ?

那么......调整 UIImage 大小的最简单方法是什么?

回答by Paul Lynch

The simplest way is to set the frame of your UIImageViewand set the contentModeto one of the resizing options.

最简单的方法是设置您的框架UIImageView并将 设置contentMode为调整大小选项之一。

Or you can use this utility method, if you actually need to resize an image:

或者,如果您确实需要调整图像大小,则可以使用此实用程序方法:

+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
    //UIGraphicsBeginImageContext(newSize);
    // In next line, pass 0.0 to use the current device's pixel scaling factor (and thus account for Retina resolution).
    // Pass 1.0 to force exact pixel size.
    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();    
    UIGraphicsEndImageContext();
    return newImage;
}

Example usage:

用法示例:

#import "MYUtil.h"
…
UIImage *myIcon = [MYUtil imageWithImage:myUIImageInstance scaledToSize:CGSizeMake(20, 20)];

回答by Rogerio Chaves

Here's a Swift version of Paul Lynch's answer

这是Paul Lynch 答案的 Swift 版本

func imageWithImage(image:UIImage, scaledToSize newSize:CGSize) -> UIImage{
    UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0);
    image.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height))
    let newImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return newImage
}

And as an extension:

作为扩展:

public extension UIImage {
    func copy(newSize: CGSize, retina: Bool = true) -> UIImage? {
        // In next line, pass 0 to use the current device's pixel scaling factor (and thus account for Retina resolution).
        // Pass 1 to force exact pixel size.
        UIGraphicsBeginImageContextWithOptions(
            /* size: */ newSize,
            /* opaque: */ false,
            /* scale: */ retina ? 0 : 1
        )
        defer { UIGraphicsEndImageContext() }

        self.draw(in: CGRect(origin: .zero, size: newSize))
        return UIGraphicsGetImageFromCurrentImageContext()
    }
}

回答by Jakub Pr??a

Proper Swift 3.0for iOS 10+solution: Using ImageRendererand closure syntax:

适用于iOS 10+ 的正确Swift 3.0解决方案:使用和闭包语法:ImageRenderer

func imageWith(newSize: CGSize) -> UIImage {
    let renderer = UIGraphicsImageRenderer(size: newSize)
    let image = renderer.image { _ in
        self.draw(in: CGRect.init(origin: CGPoint.zero, size: newSize))
    }

    return image
}

And here's the Objective-C version:

这是 Objective-C 版本:

@implementation UIImage (ResizeCategory)
- (UIImage *)imageWithSize:(CGSize)newSize
{
    UIGraphicsImageRenderer *renderer = [[UIGraphicsImageRenderer alloc] initWithSize:newSize];
    UIImage *image = [renderer imageWithActions:^(UIGraphicsImageRendererContext*_Nonnull myContext) {
        [self drawInRect:(CGRect) {.origin = CGPointZero, .size = newSize}];
    }];
    return image;
}
@end

回答by TechZen

Trevor Howard has some UIImage categoriesthat handle resize quite nicely. If nothing else you can use the code as examples.

Trevor Howard 有一些UIImage 类别可以很好地处理调整大小。如果不出意外,您可以使用代码作为示例。

Note: As of iOS 5.1, this answer maybe invalid. See comment below.

注意:从 iOS 5.1 开始,这个答案可能无效。请参阅下面的评论。

回答by neave

A more compact version for Swift 4 and iOS 10+:

更紧凑的 Swift 4 和 iOS 10+ 版本:

extension UIImage {
    func resized(to size: CGSize) -> UIImage {
        return UIGraphicsImageRenderer(size: size).image { _ in
            draw(in: CGRect(origin: .zero, size: size))
        }
    }
}

Usage:

用法:

let resizedImage = image.resized(to: CGSize(width: 50, height: 50))

回答by iwasrobbed

I've also seen this done as well (which I use on UIButtonsfor Normal and Selected state since buttons don't resizeto fit). Credit goes to whoever the original author was.

我也看到这样做了(UIButtons因为按钮不resize适合,所以我将其用于 Normal 和 Selected 状态)。归功于原作者是谁。

First make an empty .h and .m file called UIImageResizing.hand UIImageResizing.m

首先创建一个空的 .h 和 .m 文件,名为UIImageResizing.handUIImageResizing.m

// Put this in UIImageResizing.h
@interface UIImage (Resize)
- (UIImage*)scaleToSize:(CGSize)size;
@end

// Put this in UIImageResizing.m
@implementation UIImage (Resize)

- (UIImage*)scaleToSize:(CGSize)size {
UIGraphicsBeginImageContext(size);

CGContextRef context = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(context, 0.0, size.height);
CGContextScaleCTM(context, 1.0, -1.0);

CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, size.width, size.height), self.CGImage);

UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

return scaledImage;
}

@end

Include that .h file in whatever .m file you're going to use the function in and then call it like this:

将该 .h 文件包含在您要在其中使用该函数的任何 .m 文件中,然后像这样调用它:

UIImage* image = [UIImage imageNamed:@"largeImage.png"];
UIImage* smallImage = [image scaleToSize:CGSizeMake(100.0f,100.0f)];

回答by malhal

This improvement to Paul's code will give you a sharp high res image on an iPhone with a retina display. Otherwise when scaling down it's blurry.

Paul 代码的这一改进将使您在配备视网膜显示屏的 iPhone 上获得清晰的高分辨率图像。否则当按比例缩小时它是模糊的。

+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
    if ([[UIScreen mainScreen] scale] == 2.0) {
        UIGraphicsBeginImageContextWithOptions(newSize, YES, 2.0);
    } else {
        UIGraphicsBeginImageContext(newSize);
    }
} else {
    UIGraphicsBeginImageContext(newSize);
}
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();    
UIGraphicsEndImageContext();
return newImage;
}

回答by asmad

Here is a simple way:

这是一个简单的方法:

    UIImage * image = [UIImage imageNamed:@"image"];
    CGSize sacleSize = CGSizeMake(10, 10);
    UIGraphicsBeginImageContextWithOptions(sacleSize, NO, 0.0);
    [image drawInRect:CGRectMake(0, 0, sacleSize.width, sacleSize.height)];
    UIImage * resizedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

resizedImageis a new image.

resizedImage是一个新图像。

回答by Josh Bernfeld

Swift solution for Stretch Fill, Aspect Fill and Aspect Fit

Stretch Fill、Aspect Fill 和 Aspect Fit 的 Swift 解决方案

extension UIImage {
    enum ContentMode {
        case contentFill
        case contentAspectFill
        case contentAspectFit
    }

    func resize(withSize size: CGSize, contentMode: ContentMode = .contentAspectFill) -> UIImage? {
        let aspectWidth = size.width / self.size.width
        let aspectHeight = size.height / self.size.height

        switch contentMode {
        case .contentFill:
            return resize(withSize: size)
        case .contentAspectFit:
            let aspectRatio = min(aspectWidth, aspectHeight)
            return resize(withSize: CGSize(width: self.size.width * aspectRatio, height: self.size.height * aspectRatio))
        case .contentAspectFill:
            let aspectRatio = max(aspectWidth, aspectHeight)
            return resize(withSize: CGSize(width: self.size.width * aspectRatio, height: self.size.height * aspectRatio))
        }
    }

    private func resize(withSize size: CGSize) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(size, false, self.scale)
        defer { UIGraphicsEndImageContext() }
        draw(in: CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height))
        return UIGraphicsGetImageFromCurrentImageContext()
    }
}

and to use you can do the following:

并使用您可以执行以下操作:

let image = UIImage(named: "image.png")!
let newImage = image.resize(withSize: CGSize(width: 200, height: 150), contentMode: .contentAspectFill)

Thanks to abdullahselek for his original solution.

感谢 abdullahselek 的原始解决方案。

回答by Scott Means

Here's a modification of the category written by iWasRobbed above. It keeps the aspect ratio of the original image instead of distorting it.

这是上面 iWasRobbed 编写的类别的修改。它保持原始图像的纵横比而不是扭曲它。

- (UIImage*)scaleToSizeKeepAspect:(CGSize)size {
    UIGraphicsBeginImageContext(size);

    CGFloat ws = size.width/self.size.width;
    CGFloat hs = size.height/self.size.height;

    if (ws > hs) {
        ws = hs/ws;
        hs = 1.0;
    } else {
        hs = ws/hs;
        ws = 1.0;
    }

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(context, 0.0, size.height);
    CGContextScaleCTM(context, 1.0, -1.0);

    CGContextDrawImage(context, CGRectMake(size.width/2-(size.width*ws)/2,
        size.height/2-(size.height*hs)/2, size.width*ws,
        size.height*hs), self.CGImage);

    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return scaledImage;
}