我正在尝试创建内存映像,在其上绘制并保存到磁盘中.
目前的代码是:
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];发布于 2012-11-29 00:47:00
您的解决方法对于手头的任务是有效的,但是,这是一个比实际获得一个NSBitmapImageRep工作更昂贵的操作!有关讨论,请参阅http://cocoadev.com/wiki/NSBitmapImageRep。
请注意,NSGraphicsContext graphicsContextWithBitmapImageRep文档说:
“此方法只接受单个平面NSBitmapImageRep实例。”
您正在使用isPlanar设置您的NSBitmapImageRep:是的,因此它使用多个平面.把它设为不-你应该是好的去!
换言之:
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...https://stackoverflow.com/questions/12799920
复制相似问题