How to make a solid color UIImage

A lot of the new UIAppearance features allow you to customize UIKit widgets by supplying images for various parts of buttons, switches, etc. For an app I’m working on right now, the graphic designer has decided on a “flat” UI, which means many of the assets are just solid squares colors. Rather than add ton of simple PNGs to my bundle for each color and size, I though it would be easier just to construct the image in code. Because it’s a solid image, it only has to be a small one, since any scaling or stretching applied to it by graphics system will only produce a larger rectangle of the same color.

Here’s what I came up with:

  1. Create a new graphics context
  2. Fill a rectangle using UIBezierPath
  3. Get the image out of the graphics context


+ (UIImage*) imageWithColor:(UIColor*)color size:(CGSize)size
{
UIGraphicsBeginImageContext(size);
UIBezierPath* rPath = [UIBezierPath bezierPathWithRect:CGRectMake(0., 0., size.width, size.height)];
[color setFill];
[rPath fill];
UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}

view raw

gistfile1.m

hosted with ❤ by GitHub

I am sure this can be done more efficiently by creating an array of RGB values, using that array in a CGImageRef and then build a UIImage from from that CGImageRef, but I’m thinking that’d be way more code, right? Plus I am not really too sure how to go about doing that. So I’m hoping to get suggestions on how to improve this code.

And if you’re interested in trying it out, I added it as a UIImage category to my UI Utils github repo: https://github.com/mikekatz/iOS-UI-Utils.