I want to programmatically create a UIImage filled by a solid color. Does anyone have an idea of how to do this in Swift?
Another nice solution, Swift 3.0
public extension UIImage {
convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
let rect = CGRect(origin: .zero, size: size)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
color.setFill()
UIRectFill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
guard let cgImage = image?.cgImage else { return nil }
self.init(cgImage: cgImage)
}
}
Swift 2.2 compatible, is to create another constructor in UIImage, in this way:
public extension UIImage {
public convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
let rect = CGRect(origin: .zero, size: size)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
color.setFill()
UIRectFill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
guard let cgImage = image?.CGImage else { return nil }
self.init(CGImage: cgImage)
}
}
In this way you can create the custom colored-image in this way:
let redImage = UIImage(color: .redColor())
Or, optionally, create the image with a custom size:
let redImage200x200 = UIImage(color: .redColor(), size: CGSize(width: 200, height: 200))