Skip to content

Instantly share code, notes, and snippets.

@devindazzle
Created March 11, 2015 13:31
Show Gist options
  • Save devindazzle/0ade3af144cdc701a7aa to your computer and use it in GitHub Desktop.
Save devindazzle/0ade3af144cdc701a7aa to your computer and use it in GitHub Desktop.
Extension of UIImage to create a new UIImage with a given size and color
extension UIImage {
convenience init?(size: CGSize, color: UIColor) {
// Create a rect for this context
var rect = CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height)
// Generate the texture
// Start image context with the given size
UIGraphicsBeginImageContext(size)
// Get a reference to the context that was just created
let context = UIGraphicsGetCurrentContext()
// Clear the image context
CGContextSetFillColorWithColor(context, color.CGColor)
CGContextFillRect(context, rect)
// Get an UIImage from the context containing the texture
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
// Generate the UIImage
self.init(CGImage: image.CGImage)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment