首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >基于NSBitmapImageRep的绘图

基于NSBitmapImageRep的绘图
EN

Stack Overflow用户
提问于 2012-10-09 12:20:35
回答 1查看 2.6K关注 0票数 4

我正在尝试创建内存映像,在其上绘制并保存到磁盘中.

目前的代码是:

代码语言:javascript
复制
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];

当试图在当前上下文中绘制时,我得到了错误

代码语言:javascript
复制
CGContextSetFillColorWithColor: invalid context 0x0

这里怎么了?为什么NSBitmapImageRep返回的上下文为NULL?创建绘制图像并保存它的最佳方法是什么?

更新:

最后得出了以下解决方案:

代码语言:javascript
复制
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];
EN

回答 1

Stack Overflow用户

发布于 2012-11-29 00:47:00

您的解决方法对于手头的任务是有效的,但是,这是一个比实际获得一个NSBitmapImageRep工作更昂贵的操作!有关讨论,请参阅http://cocoadev.com/wiki/NSBitmapImageRep

请注意,NSGraphicsContext graphicsContextWithBitmapImageRep文档说:

“此方法只接受单个平面NSBitmapImageRep实例。”

您正在使用isPlanar设置您的NSBitmapImageRep:是的,因此它使用多个平面.把它设为不-你应该是好的去!

换言之:

代码语言:javascript
复制
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...
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12799920

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档