Huy Pham Huy Pham - 6 months ago 56
iOS Question

Create UIImage with solid color in Swift

I want to programmatically create an UIImage filled by a solid color. Anyone have an idea of how to do this in Swift?

Answer

Here's another option. I believe you wanted an exact UIImage object.

func getImageWithColor(color: UIColor, size: CGSize) -> UIImage {
    let rect = CGRectMake(0, 0, size.width, size.height)
    UIGraphicsBeginImageContextWithOptions(size, false, 0)
    color.setFill()
    UIRectFill(rect)
    let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image
}

Stick this in your Swift code and call it

Comments