Created
March 26, 2017 11:44
-
-
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
This file contains 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
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