How do I create an NSBitmapImageRep from scratch?
First: I want to use NSBezierPath
to draw some simple buttons in my application, so I suppose I have to create NSBitmapImageRep
, get CGImage
, create NSImage
and then call setImage: on the button. Correct me if I am wrong.
So I went to see how to create NSBitmapImage
and found this:
**initWithBitmapDataPlanes:pixelsWide:pixelsHigh:bitsPerSample:samplesPerPixel:hasAlpha:isPlanar:colorSpaceName:bitmapFormat:bytesPerRow:bitsPerPixel:**
Wow.
Remembering that what I was looking for was something like a string initWithSize:
, what should I use for these values?
source to share
Any specific reason why you don't just create a new one NSImage
and draw into it by copying the focus-locked drawing code like
NSImage* anImage = [[NSImage alloc] initWithSize:NSMakeSize(100.0, 100.0)];
[anImage lockFocus];
// Do your drawing here...
[anImage unlockFocus];
( Cocoa Drawing Guide is your friend by the way)
source to share
The documentation explains it pretty well.
The parameter is a planes
little confusing. It's basically a pointer to a pointer to pixels. So if you have pixels in an array pointed to by a variable named "pixels", for example:
unsigned char* pixels = malloc (width * height * 4); // assumes ARGB 8-bit pixels
NSBitmapImageRep* myImageRep = [[NSBitmapImageRep alloc] initWithDataPlanes:&pixels
... etc...];
The rest of the parameters are pretty simple. pixelWidth
and pixelHeight
is what you expect. The rest of the values ββcorrespond to how your data is ordered. Are you using 8 bits per channel ARGB data? Or is it RGBA at 32 bits per channel?
NSDeviceRGBColorSpace
probably sufficient for use in a color space.
A pipe isPlanar
must be NO
if you are passing a single pointer to your image data.
source to share
You don't need to allocate space for the data planes. Below is the call to create an empty 32 bit NSBitmapImageRep
with alpha component.
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];
source to share