Created
March 14, 2018 11:22
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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