【问题标题】:How do you draw to a CGContextRef and save as png?你如何绘制到 CGContextRef 并保存为 png?
【发布时间】:2012-05-31 02:25:12
【问题描述】:

我有一个绘制到给定 CGContextRef 的 void,它通常在自定义视图的 drawRect 例程中提供,但是我还需要生成一个可以绘制到的 CGContextRef,这样我就可以将生成的图像保存为一个 PNG 文件。

【问题讨论】:

标签: objective-c macos cocoa


【解决方案1】:

原来这很简单:

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];

【讨论】:

  • 这让我崩溃了(os x Yosemite,Xcode 6)。幸运的是,我在这个问题中找到了 cobbal 的答案:*.com/questions/12223739/…