Skip to content

Instantly share code, notes, and snippets.

@mteera
Created March 14, 2018 11:22
Show Gist options
  • Save mteera/691876f3e6e2a34e9c09eb2af4cc0435 to your computer and use it in GitHub Desktop.
Save mteera/691876f3e6e2a34e9c09eb2af4cc0435 to your computer and use it in GitHub Desktop.
A function to let you resize UIImage for example for a the imageView on a UITableViewCell
func resizeImageWith(image: UIImage, newSize: CGSize) -> UIImage {
let horizontalRatio = newSize.width / image.size.width
let verticalRatio = newSize.height / image.size.height
let ratio = max(horizontalRatio, verticalRatio)
let newSize = CGSize(width: image.size.width * ratio, height: image.size.height * ratio)
var newImage: UIImage
if #available(iOS 10.0, *) {
let renderFormat = UIGraphicsImageRendererFormat.default()
renderFormat.opaque = false
let renderer = UIGraphicsImageRenderer(size: CGSize(width: newSize.width, height: newSize.height), format: renderFormat)
newImage = renderer.image {
(context) in
image.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
}
} else {
UIGraphicsBeginImageContextWithOptions(CGSize(width: newSize.width, height: newSize.height), true, 0)
image.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
newImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
}
return newImage
}
// Usage: image = resizeImageWith(image: image!, newSize: CGSize(width: 30, height: 30))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment