Skip to content

Instantly share code, notes, and snippets.

@binhwpo
Created March 10, 2017 17:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save binhwpo/dc698e982894a74a225f621d5467503b to your computer and use it in GitHub Desktop.
Save binhwpo/dc698e982894a74a225f621d5467503b to your computer and use it in GitHub Desktop.
Swift resizeImage function
func resizeImage(image: UIImage, newSize: CGSize) -> UIImage {
let imageSize = image.size
let width = imageSize.width
let height = imageSize.height
let widthFactor = newSize.width/width
let heightFactor = newSize.height/height
let scaledFactor = (widthFactor < heightFactor) ? widthFactor : heightFactor
let scaledWidth = width * scaledFactor
let scaledHeight = height * scaledFactor
let targetSize = CGSize(width: scaledWidth, height: scaledHeight)
UIGraphicsBeginImageContext(targetSize)
image.draw(in: CGRect(x: 0, y: 0, width: scaledWidth, height: scaledHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
return newImage!
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment