Ios – UIImage resizing scale

iosswiftuiimageuiimageview

I have an image like this:

Have a look at this image

and I'd like to resize this image to a specific width: let's say 200px where the height should also get calculated. (So the image should keep its width-to-height scale)

This was all I get so far:

extension UIImage {
    func resize(newSize1: CGSize) -> UIImage {
        let size = self.size
        let widthRatio  = newSize1.width  / size.width
        let heightRatio = newSize1.height / size.height

        var newSize2: CGSize
        if(widthRatio > heightRatio) {
            newSize2 = CGSize(width: size.width * heightRatio, height: size.height * heightRatio)
        } else {
            newSize2 = CGSize(width: size.width * widthRatio,  height: size.height * widthRatio)
        }
        let rect = CGRect(x: 0, y: 0, width: newSize2.width, height: newSize2.height)
        UIGraphicsBeginImageContextWithOptions(newSize2, false, 1.0)
        self.draw(in: rect)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage2!
    }
}

But the function takes a CGSize size parameter (width AND height) but I just want to get a function that takes the width parameter.

How to edit my code to solve my problem?
Any help would be very appreciated :)

Note: The UIImage should get a smaller resolution (less pixels), not the Image View itself!

Best Answer

For Swift 4 And Swift 3 use below UIImage extension for resizing image. It's calculated height according to given width.

extension UIImage {
    func resized(toWidth width: CGFloat) -> UIImage? {
        let canvasSize = CGSize(width: width, height: CGFloat(ceil(width/size.width * size.height)))
        UIGraphicsBeginImageContextWithOptions(canvasSize, false, scale)
        defer { UIGraphicsEndImageContext() }
        draw(in: CGRect(origin: .zero, size: canvasSize))
        return UIGraphicsGetImageFromCurrentImageContext()
    }
}
Related Topic