Skip to content

Instantly share code, notes, and snippets.

@konnnn
Last active June 30, 2019 09:59
Show Gist options
  • Save konnnn/6f1622f6071e2c05064e72540c527a8e to your computer and use it in GitHub Desktop.
Save konnnn/6f1622f6071e2c05064e72540c527a8e to your computer and use it in GitHub Desktop.
// Created by Evgeny Konkin on 17.06.2019.
extension UIImage {
/// Resize image to new size ::byKonnn
func resizeImage(to newImageSize: CGSize) -> UIImage {
// Guard newSize is different
guard self.size != newImageSize else { return self }
let widthRatio = newImageSize.width / self.size.width
let heightRatio = newImageSize.height / self.size.height
// Figure out what our orientation is, and use that to form the rectangle
var newSize: CGSize
if(widthRatio > heightRatio) {
newSize = CGSize(width: self.size.width * heightRatio, height: self.size.height * heightRatio)
} else {
newSize = CGSize(width: self.size.width * widthRatio, height: self.size.height * widthRatio)
}
// This is the rect that we've calculated out and this is what is actually used below
let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)
// Actually do the resizing to the rect using the ImageContext stuff
UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
self.draw(in: rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
}
// How to use
let imageView = UIImageView()
imageView.image = UIImage(named: "some_image_name")?.resizeImage(to: CGSize(width: 41, height: 41))
// ::byKonnn
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment