Created
November 24, 2017 05:03
-
-
Save oalansari82/8b66fb244b5d0e4401793cf5306e7b9b to your computer and use it in GitHub Desktop.
Resize images in swift
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 resizeWithPercent(percentage: CGFloat) -> UIImage? { | |
| let imageView = UIImageView(frame: CGRect(origin: .zero, size: CGSize(width: size.width * percentage, height: size.height * percentage))) | |
| imageView.contentMode = .scaleAspectFit | |
| imageView.image = self | |
| UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, scale) | |
| guard let context = UIGraphicsGetCurrentContext() else { return nil } | |
| imageView.layer.render(in: context) | |
| guard let result = UIGraphicsGetImageFromCurrentImageContext() else { return nil } | |
| UIGraphicsEndImageContext() | |
| return result | |
| } | |
| func resizeWithWidth(width: CGFloat) -> UIImage? { | |
| let imageView = UIImageView(frame: CGRect(origin: .zero, size: CGSize(width: width, height: CGFloat(ceil(width/size.width * size.height))))) | |
| imageView.contentMode = .scaleAspectFit | |
| imageView.image = self | |
| UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, scale) | |
| guard let context = UIGraphicsGetCurrentContext() else { return nil } | |
| imageView.layer.render(in: context) | |
| guard let result = UIGraphicsGetImageFromCurrentImageContext() else { return nil } | |
| UIGraphicsEndImageContext() | |
| return result | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment