Zlo*_*erg 2 macos cocoa drawing
我正在尝试创建内存映像,在其上绘制并保存到磁盘.
目前的代码是:
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];
Run Code Online (Sandbox Code Playgroud)
当试图在当前上下文中绘制时,我收到错误
CGContextSetFillColorWithColor: invalid context 0x0
Run Code Online (Sandbox Code Playgroud)
这有什么不对?为什么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];
Run Code Online (Sandbox Code Playgroud)
您的解决方法对于手头的任务是有效的,但是,它实际上比实际使NSBitmapImageRep工作更昂贵!有关讨论,请参阅http://cocoadev.com/wiki/NSBitmapImageRep.
请注意,[ NSGraphicsContext graphicsContextWithBitmapImageRep:]文档说:
"此方法仅接受单个平面NSBitmapImageRep实例."
您正在使用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...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2177 次 |
| 最近记录: |