如何从头开始创建NSBitmapImageRep?

时间:2014-08-05 00:48:24

标签: image cocoa nsbezierpath nsbitmapimagerep

首先关闭:我想使用NSBezierPath在我的应用中绘制一些简单的按钮图片,所以我想我应该创建一个NSBitmapImageRep,得到{{1从中创建一个CGImage,然后在按钮上调用setImage:。如果我错了,请纠正我。

所以我去了解如何创建NSImage并找到了这个: NSBitmapImage

哇。

记住我所寻找的东西是**initWithBitmapDataPlanes:pixelsWide:pixelsHigh:bitsPerSample:samplesPerPixel:hasAlpha:isPlanar:colorSpaceName:bitmapFormat:bytesPerRow:bitsPerPixel:**的内容,我应该为这些值添加什么?

3 个答案:

答案 0 :(得分:1)

The documentation很好地解释了这一点。

planes参数有点令人困惑。它基本上是指向像素指针的指针。因此,如果您的像素位于由名为“pixels”的变量指向的数组中,请执行以下操作:

unsigned char* pixels = malloc (width * height * 4); // assumes ARGB 8-bit pixels
NSBitmapImageRep* myImageRep = [[NSBitmapImageRep alloc] initWithDataPlanes:&pixels
... etc...];

其余参数非常简单。 pixelWidthpixelHeight正是您所期望的。其他值都与您的数据排列方式相对应。您是否每通道使用8位ARGB数据?或者它是每通道32位的RGBA?

NSDeviceRGBColorSpace可能足以用于色彩空间。

如果您传递一个指向图像数据的指针,则isPlanar频道应为NO

答案 1 :(得分:1)

任何特殊原因,您不是简单地创建一个新的NSImage并通过将您的绘图代码包含在焦点锁定中来绘制它,如

NSImage* anImage = [[NSImage alloc] initWithSize:NSMakeSize(100.0,  100.0)];
[anImage lockFocus];

// Do your drawing here...

[anImage unlockFocus];

Cocoa Drawing Guide是你的朋友,顺便说一句)

答案 2 :(得分:0)

您无需为数据平面分配空间。下面是调用创建一个带有alpha分量的空32位NSBitmapImageRep

NSBitmapImageRep *newRep = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL
                                                                   pixelsWide:pixelsWide
                                                                   pixelsHigh:pixelsHigh
                                                                bitsPerSample:8
                                                              samplesPerPixel:4
                                                                     hasAlpha:YES
                                                                     isPlanar:NO
                                                               colorSpaceName:NSDeviceRGBColorSpace
                                                                   bytesPerRow:4 * pixelsWide
                                                                  bitsPerPixel:32];
相关问题