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:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
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 […]