UIImage vs NSImage: Drawing to an off screen image in iOS

mtmurdock picture mtmurdock · Mar 22, 2012 · Viewed 7k times · Source

In mac osx (cocoa), It is very easy to make a blank image of a specific size and draw to it off screen:

NSImage* image = [[NSImage alloc] initWithSize:NSMakeSize(64,64)];
[image lockFocus];
/* drawing code here */
[image unlockFocus];

However, in iOS (cocoa touch) there does not seem to be equivalent calls for UIImage. I want to use UIImage (or some other equivalent class) to do the same thing. That is, I want to make an explicitly size, initially empty image to which I can draw using calls like UIRectFill(...) and [UIBezierPath stroke].

How would I do this?

Answer

Richard J. Ross III picture Richard J. Ross III · Mar 22, 2012

CoreGraphics is needed here, as UIImage does not have high level functions like what you explained..

UIGraphicsBeginImageContext(CGSizeMake(64,64));

CGContextRef context = UIGraphicsGetCurrentContext();
// drawing code here (using context)

UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();