Last active
February 28, 2019 10:33
-
-
Save ElegyD/b40d5f2f375d57cc17d24081b9aee482 to your computer and use it in GitHub Desktop.
Extension to resize an UIImage to a maximum width/height while keeping the aspect ratio in Swift 4.
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
| extension UIImage { | |
| func resized(to maxSize: CGFloat) -> UIImage? { | |
| var size = self.size | |
| if size.width <= maxSize && size.height <= maxSize { | |
| return self | |
| } | |
| let scaleFactor = maxSize / max(size.width, size.height) | |
| size.width *= scaleFactor | |
| size.height *= scaleFactor | |
| UIGraphicsBeginImageContext(size) | |
| self.draw(in: CGRect(origin: .zero, size: size)) | |
| let newImage = UIGraphicsGetImageFromCurrentImageContext() | |
| UIGraphicsEndImageContext() | |
| return newImage | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment