Skip to content

Instantly share code, notes, and snippets.

@KyleGoslan
Created November 27, 2016 21:47
Show Gist options
  • Save KyleGoslan/f22009a21de41e716301769cb3039400 to your computer and use it in GitHub Desktop.
Save KyleGoslan/f22009a21de41e716301769cb3039400 to your computer and use it in GitHub Desktop.
Resize UIImage Swift 3
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