Ich versuche, ein Bild im Speicher zu erstellen, darauf zu zeichnen und auf der Festplatte zu speichern.
Aktueller Code:
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];
beim Versuch, im aktuellen Kontext zu zeichnen, erhalte ich einen Fehler
CGContextSetFillColorWithColor: ungültiger Kontext 0x0
Was ist hier falsch? Warum ist der Kontext, der von NSBitmapImageRep zurückgegeben wird, NULL? Was ist der beste Weg, um ein gezeichnetes Bild zu erstellen und zu speichern?
UPDATE:
Schließlich kam ich zu folgender Lösung:
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];