The simplest way to resize an UIImage?

前端 未结 30 2602
迷失自我
迷失自我 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:52

    I've discovered that it's difficult to find an answer that you can use out-of-the box in your Swift 3 project. The main problem of other answers that they don't honor the alpha-channel of the image. Here is the technique that I'm using in my projects.

    extension UIImage {
    
        func scaledToFit(toSize newSize: CGSize) -> UIImage {
            if (size.width < newSize.width && size.height < newSize.height) {
                return copy() as! UIImage
            }
    
            let widthScale = newSize.width / size.width
            let heightScale = newSize.height / size.height
    
            let scaleFactor = widthScale < heightScale ? widthScale : heightScale
            let scaledSize = CGSize(width: size.width * scaleFactor, height: size.height * scaleFactor)
    
            return self.scaled(toSize: scaledSize, in: CGRect(x: 0.0, y: 0.0, width: scaledSize.width, height: scaledSize.height))
        }
    
        func scaled(toSize newSize: CGSize, in rect: CGRect) -> UIImage {
            if UIScreen.main.scale == 2.0 {
                UIGraphicsBeginImageContextWithOptions(newSize, !hasAlphaChannel, 2.0)
            }
            else {
                UIGraphicsBeginImageContext(newSize)
            }
    
            draw(in: rect)
            let newImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
    
            return newImage ?? UIImage()
        }
    
        var hasAlphaChannel: Bool {
            guard let alpha = cgImage?.alphaInfo else {
                return false
            }
            return alpha == CGImageAlphaInfo.first ||
                alpha == CGImageAlphaInfo.last ||
                alpha == CGImageAlphaInfo.premultipliedFirst ||
                alpha == CGImageAlphaInfo.premultipliedLast
        }
    }
    

    Example of usage:

    override func viewDidLoad() {
        super.viewDidLoad()
    
        let size = CGSize(width: 14.0, height: 14.0)
        if let image = UIImage(named: "barbell")?.scaledToFit(toSize: size) {
            let imageView = UIImageView(image: image)
            imageView.center = CGPoint(x: 100, y: 100)
            view.addSubview(imageView)
        }
    }
    

    This code is a rewrite of Apple's extension with added support for images with and without alpha channel.

    As a further reading I recommend checking this article for different image resizing techniques. Current approach offers decent performance, it operates high-level APIs and easy to understand. I recommend sticking to it unless you find that image resizing is a bottleneck in your performance.

提交回复
热议问题