Skip to content

Instantly share code, notes, and snippets.

@avdyushin
Last active May 31, 2016 11:33
Show Gist options
  • Save avdyushin/fee93bb8d56747f599fee91da6d6e869 to your computer and use it in GitHub Desktop.
Save avdyushin/fee93bb8d56747f599fee91da6d6e869 to your computer and use it in GitHub Desktop.
UIImage missed resize method via Swift extensions
extension UIImage {
convenience init?(color: UIColor, size: CGSize = CGSizeMake(1, 1)) {
let rect = CGRectMake(0, 0, size.width, size.height)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0)
let context = UIGraphicsGetCurrentContext()
CGContextSetFillColorWithColor(context, color.CGColor)
CGContextFillRect(context, rect)
self.init(CGImage: UIGraphicsGetImageFromCurrentImageContext().CGImage!)
UIGraphicsEndImageContext()
}
public func resize(width: CGFloat) -> UIImage {
let scale = width / self.size.width
let height = self.size.height * scale
UIGraphicsBeginImageContextWithOptions(CGSizeMake(width, height), false, UIScreen.mainScreen().scale)
self.drawInRect(CGRectMake(0, 0, width, height))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment