Swift 4: scale image to width

For an app that I was writing I needed an easy function to scale an image to a specific width, the function below will accomplish this:

func scaleImageWidth(sourceImage:UIImage, scaledToWidth: CGFloat) -> UIImage {
    let oldWidth = sourceImage.size.width
    let scaleFactor = scaledToWidth / oldWidth
        
    let newHeight = sourceImage.size.height * scaleFactor
    let newWidth = oldWidth * scaleFactor
        
    UIGraphicsBeginImageContext(CGSize(width:newWidth, height:newHeight))
    sourceImage.draw(in: CGRect(x:0, y:0, width:newWidth, height:newHeight))
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return newImage!
}

I can guarantee you that I did not come up with that function, but I can no longer recall, where I got it from. Most likely place is Stack Overflow 🙂

Swift 4: scale image to width
Scroll to top