Josiah Josiah - 1 year ago 102
Objective-C Question

How can I make an UIImage programatically?

This isn't what you probably thought it was to begin with. I know how to use UIImage's, but I now need to know how to create a "blank" UIImage using:

CGRect screenRect = [self.view bounds];

Well, those dimensions. Anyway, I want to know how I can create a UIImage with those dimensions colored all white. No actual images here.

Is this even possible? I am sure it is, but maybe I am wrong.


This needs to be a "white" image. Not a blank one. :)

Answer Source

You need to use CoreGraphics, as follows.

CGSize size = CGSizeMake(desiredWidth, desiredHeight);
UIGraphicsBeginImageContextWithOptions(size, YES, 0);
[[UIColor whiteColor] setFill];
UIRectFill(CGRectMake(0, 0, size.width, size.height));
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

The code creates a new CoreGraphics image context with the options passed as parameters; size, opaqueness, and scale. By passing 0 for scale, iOS automatically chooses the appropriate value for the current device.

Then, the context fill colour is set to [UIColor whiteColor]. Immediately, the canvas is then actually filled with that color, by using UIRectFill() and passing a rectangle which fills the canvas.

A UIImage is then created of the current context, and the context is closed. Therefore, the image variable contains a UIImage of the desired size, filled white.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download