Skip to content

Instantly share code, notes, and snippets.

@ElegyD
Last active February 28, 2019 10:33
Show Gist options
  • Select an option

  • Save ElegyD/b40d5f2f375d57cc17d24081b9aee482 to your computer and use it in GitHub Desktop.

Select an option

Save ElegyD/b40d5f2f375d57cc17d24081b9aee482 to your computer and use it in GitHub Desktop.
Extension to resize an UIImage to a maximum width/height while keeping the aspect ratio in Swift 4.
extension UIImage {
func resized(to maxSize: CGFloat) -> UIImage? {
var size = self.size
if size.width <= maxSize && size.height <= maxSize {
return self
}
let scaleFactor = maxSize / max(size.width, size.height)
size.width *= scaleFactor
size.height *= scaleFactor
UIGraphicsBeginImageContext(size)
self.draw(in: CGRect(origin: .zero, size: size))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment