2

I've got a void that draws to a given CGContextRef that is usually supplied in the drawRect routine of a custom view however I also need to generate a CGContextRef that it can draw to that would allow me to save the resulting image as a PNG file.

Thomas Denney
  • 1,578
  • 2
  • 15
  • 25

1 Answers1

4

Turns out it was pretty simple:

NSImage *toSave = [[NSImage alloc] initWithSize:CGSizeMake(600, 900)];

[toSave lockFocus];

CGContextRef context = [[NSGraphicsContext currentContext] graphicsPort];

//drawing code

[toSave unlockFocus];

NSBitmapImageRep *imgRep = [[toSave representations] objectAtIndex: 0];

NSData *data = [imgRep representationUsingType: NSPNGFileType properties: nil];

[data writeToFile: @"/path/to/file.png" atomically: NO];
Thomas Denney
  • 1,578
  • 2
  • 15
  • 25
  • This crashed on me (os x Yosemite, Xcode 6). Luckily I found cobbal's answer in this question: http://stackoverflow.com/questions/12223739/ios-to-mac-graphiccontext-explanation-conversion – CodeBrew May 25 '15 at 05:05