12

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?

mtmurdock
  • 12,756
  • 21
  • 65
  • 108

3 Answers3

9

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();
Richard J. Ross III
  • 55,009
  • 24
  • 135
  • 201
3

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.

sch
  • 27,436
  • 3
  • 68
  • 83
0

Something like this:

UIGraphicsBeginImageContextWithOptions(mySize, NO, 0.0f);       
CGContextRef context = UIGraphicsGetCurrentContext();
UIGraphicsPushContext(context);

[myImage drawInRect:myImageRect];
[myText drawAtPoint:myOrigin withFont:myFont];

UIGraphicsPopContext();
UIImage *myNewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
Dave Batton
  • 8,795
  • 1
  • 46
  • 50
  • Notice you'll want to use UIGraphicsBeginImageContextWithOptions rather than UIGraphicsBeginImageContext, so that you draw in the scale supported by the device. Using UIGraphicsBeginImageContext will look poor on a retina display. – Dave Batton Mar 22 '12 at 20:02
  • 2
    `UIGraphicsPushContext(context);` and `UIGraphicsPopContext();` can be removed because `UIGraphicsBeginImageContextWithOptions(mySize, NO, 0.0f);` and `UIGraphicsEndImageContext();` already do that. – sch Mar 22 '12 at 20:11