I'm trying to create in-memory image, draw on it and save to disk.
Current code is:
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];
when trying to draw in current context, I'm getting error
CGContextSetFillColorWithColor: invalid context 0x0
What is wrong here? Why context returned by NSBitmapImageRep is NULL? What is the best way to create drawn image and save it?
UPDATE:
Finally came to following solution:
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];
Your workaround is valid for the task at hand, however, it's a more expensive operation than actually getting an NSBitmapImageRep to work! See http://cocoadev.com/wiki/NSBitmapImageRep for a bit of a discussion..
Notice that [NSGraphicsContext graphicsContextWithBitmapImageRep:] documentation says:
"This method accepts only single plane NSBitmapImageRep instances."
You are setting up your NSBitmapImageRep with isPlanar:YES, which therefore uses multiple planes... Set it to NO - you should be good to go!
In other words:
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With