Last active
May 31, 2016 11:33
-
-
Save avdyushin/fee93bb8d56747f599fee91da6d6e869 to your computer and use it in GitHub Desktop.
UIImage missed resize method via Swift extensions
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 { | |
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