The simplest way to resize an UIImage?

前端 未结 30 2643
迷失自我
迷失自我 2020-11-21 22:38

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 :

UIImage *newI         


        
相关标签:
30条回答
  • 2020-11-21 22:56

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

    First make an empty .h and .m file called UIImageResizing.h and UIImageResizing.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:

    UIImage* image = [UIImage imageNamed:@"largeImage.png"];
    UIImage* smallImage = [image scaleToSize:CGSizeMake(100.0f,100.0f)];
    
    0 讨论(0)
  • 2020-11-21 22:57

    This is an UIImage extension compatible with Swift 3 and Swift 4 which scales image to given size with an aspect ratio

    extension UIImage {
    
        func scaledImage(withSize size: CGSize) -> UIImage {
            UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
            defer { UIGraphicsEndImageContext() }
            draw(in: CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height))
            return UIGraphicsGetImageFromCurrentImageContext()!
        }
    
        func scaleImageToFitSize(size: CGSize) -> UIImage {
            let aspect = self.size.width / self.size.height
            if size.width / aspect <= size.height {
                return scaledImage(withSize: CGSize(width: size.width, height: size.width / aspect))
            } else {
                return scaledImage(withSize: CGSize(width: size.height * aspect, height: size.height))
            }
        }
    
    }
    

    Example usage

    let image = UIImage(named: "apple")
    let scaledImage = image.scaleImageToFitSize(size: CGSize(width: 45.0, height: 45.0))
    
    0 讨论(0)
  • 2020-11-21 22:59

    Swift solution for Stretch Fill, Aspect Fill and Aspect Fit

    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.

    0 讨论(0)
  • 2020-11-21 23:00

    A more compact version for Swift 4 and 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))
    
    0 讨论(0)
  • 2020-11-21 23:01

    (Swift 4 compatible) iOS 10+ and iOS < 10 solution (using UIGraphicsImageRenderer if possible, UIGraphicsGetImageFromCurrentImageContext otherwise)

    /// Resizes an image
    ///
    /// - Parameter newSize: New size
    /// - Returns: Resized image
    func scaled(to newSize: CGSize) -> UIImage {
        let rect = CGRect(origin: .zero, size: newSize)
    
        if #available(iOS 10, *) {
            let renderer = UIGraphicsImageRenderer(size: newSize)
            return renderer.image { _ in
                self.draw(in: rect)
            }
        } else {
            UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
            self.draw(in: rect)
            let newImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return newImage!
        }
    }
    
    0 讨论(0)
  • 2020-11-21 23:02

    @Paul Lynch's answer is great, but it would change the image ratio. if you don`t want to change the image ratio, and still want the new image fit for new size, try this.

    + (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
    
    // calculate a new size which ratio is same to original image
    CGFloat ratioW = image.size.width / newSize.width;
    CGFloat ratioH = image.size.height / newSize.height;
    
    CGFloat ratio = image.size.width / image.size.height;
    
    CGSize showSize = CGSizeZero;
    if (ratioW > 1 && ratioH > 1) { 
    
        if (ratioW > ratioH) { 
            showSize.width = newSize.width;
            showSize.height = showSize.width / ratio;
        } else {
            showSize.height = newSize.height;
            showSize.width = showSize.height * ratio;
        }
    
    } else if (ratioW > 1) {
    
        showSize.width = showSize.width;
        showSize.height = showSize.width / ratio;
    
    } else if (ratioH > 1) {
    
        showSize.height = showSize.height;
        showSize.width = showSize.height * ratio;
    
    }
    
    //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(showSize, NO, 0.0);
    [image drawInRect:CGRectMake(0, 0, showSize.width, showSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;}
    
    0 讨论(0)
提交回复
热议问题