Created
November 27, 2016 21:47
-
-
Save KyleGoslan/f22009a21de41e716301769cb3039400 to your computer and use it in GitHub Desktop.
Resize UIImage 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
import UIKit | |
extension UIImage { | |
func resizeWith(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 resizeWith(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