Skip to content

Instantly share code, notes, and snippets.

@Haeuncs
Last active August 1, 2019 03:06
Show Gist options
  • Save Haeuncs/b0f98c1b31769212468b00216f7d4be9 to your computer and use it in GitHub Desktop.
Save Haeuncs/b0f98c1b31769212468b00216f7d4be9 to your computer and use it in GitHub Desktop.
extension UIImage {
func resized(toWidth width: CGFloat) -> UIImage? {
let canvasSize = CGSize(width: width, height: CGFloat(ceil(width/size.width * size.height)))
UIGraphicsBeginImageContextWithOptions(canvasSize, false, scale)
defer { UIGraphicsEndImageContext() }
draw(in: CGRect(origin: .zero, size: canvasSize))
return UIGraphicsGetImageFromCurrentImageContext()
}
func resizedImageWith(targetSize: CGSize) -> UIImage {
let imageSize = self.size
let newWidth = targetSize.width / self.size.width
let newHeight = targetSize.height / self.size.height
var newSize: CGSize
if(newWidth > newHeight) {
newSize = CGSize(width: imageSize.width * newHeight, height: imageSize.height * newHeight)
} else {
newSize = CGSize(width: imageSize.width * newWidth, height: imageSize.height * newWidth)
}
let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
self.draw(in: rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return newImage
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment