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.
Asked
Active
Viewed 3,729 times
2
-
possible duplicate of [How Do I Save What I have Drawn In A CGContext](http://stackoverflow.com/questions/2568421/how-do-i-save-what-i-have-drawn-in-a-cgcontext) – Amy Worrall May 30 '12 at 07:49
-
@Danich nope, this is about OSX, not iOS. – Richard J. Ross III May 30 '12 at 18:25
1 Answers
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