Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 411
mtmurdock Avatar asked Mar 22 '12 19:03

mtmurdock


2 Answers

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();
like image 162
Richard J. Ross III Avatar answered Nov 05 '22 22:11

Richard J. Ross III


You can do that as follows:

UIGraphicsBeginImageContext(CGSizeMake(64, 64));
//Drawing code here
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

Here is Apple's Graphics and Drawing reference.

like image 40
sch Avatar answered Nov 05 '22 21:11

sch