我正在尝试创建内存中图像,在其上绘制并保存到磁盘。
当前代码是:
NSBitmapImageRep *rep = [[NSBitmapImageRep alloc]
initWithBitmapDataPlanes:NULL
pixelsWide:256
pixelsHigh:256
bitsPerSample:8
samplesPerPixel:4
hasAlpha:YES
isPlanar:YES
colorSpaceName:NSDeviceRGBColorSpace
bitmapFormat:NSAlphaFirstBitmapFormat
bytesPerRow:0
bitsPerPixel:8
];
[NSGraphicsContext saveGraphicsState];
[NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithBitmapImageRep:rep]];
// Draw your content...
NSRect aRect=NSMakeRect(10.0,10.0,30.0,30.0);
NSBezierPath *thePath=[NSBezierPath bezierPathWithRect:aRect];
[[NSColor redColor] set];
[thePath fill];
[NSGraphicsContext restoreGraphicsState];
NSData *data = [rep representationUsingType: NSPNGFileType properties: nil];
[data writeToFile: @"test.png" atomically: NO];
尝试在当前上下文中绘制时,出现错误
CGContextSetFillColorWithColor: invalid context 0x0
这里出了什么问题?为什么 NSBitmapImageRep 返回的上下文为 NULL? 创建绘制图像并保存它的最佳方法是什么?
更新:
最终得出以下解决方案:
NSImage *image = [[NSImage alloc] initWithSize:NSMakeSize(256, 256)];
[image lockFocus];
NSRect aRect=NSMakeRect(10.0,10.0,30.0,30.0);
NSBezierPath *thePath=[NSBezierPath bezierPathWithRect:aRect];
[[NSColor redColor] set];
[thePath fill];
[image unlockFocus];
NSData *data = [image TIFFRepresentation];
[data writeToFile: @"test.png" atomically: NO];
最佳答案
您的解决方法对于当前的任务是有效的,但是,它是比实际让 NSBitmapImageRep 工作更昂贵的操作!请参阅http://cocoadev.com/wiki/NSBitmapImageRep进行一些讨论..
请注意,[NSGraphicsContext graphicsContextWithBitmapImageRep:] 文档说:
"This method accepts only single plane NSBitmapImageRep instances."
您正在使用 isPlanar:YES 设置您的 NSBitmapImageRep,因此它使用多个平面...将其设置为 NO - 您应该可以开始了!
换句话说:
NSBitmapImageRep *rep = [[NSBitmapImageRep alloc]
initWithBitmapDataPlanes:NULL
pixelsWide:256
pixelsHigh:256
bitsPerSample:8
samplesPerPixel:4
hasAlpha:YES
isPlanar:NO
colorSpaceName:NSDeviceRGBColorSpace
bitmapFormat:NSAlphaFirstBitmapFormat
bytesPerRow:0
bitsPerPixel:0
];
// etc...
关于macos - 在 NSBitmapImageRep 上绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12799920/