Skip to content

Instantly share code, notes, and snippets.

@eleev
Created March 26, 2017 11:44
Show Gist options
  • Save eleev/fb5f7bfe1d6129e77f37030ac51c4e16 to your computer and use it in GitHub Desktop.
Save eleev/fb5f7bfe1d6129e77f37030ac51c4e16 to your computer and use it in GitHub Desktop.
Class-level extension for UIImage that allow to resize input image based on expected image width or/and height. Swift 3
extension UIImage {
class func resize(_ image: UIImage, newWidth: CGFloat) -> UIImage? {
let scale = newWidth / image.size.width
let newHeight = image.size.height * scale
UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight))
image.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
class func resize(_ image: UIImage, newHeight: CGFloat) -> UIImage? {
let scale = newHeight / image.size.height
let newWidth = image.size.width * scale
UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight))
image.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
class func resize(_ image: UIImage, newSize: CGSize) -> UIImage? {
UIGraphicsBeginImageContext(newSize)
image.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment