Daniel
Daniel

Reputation: 31609

How to draw to a file in objective-c

How can I draw to an image in objective-c? all I need to do is create an image with a size I set, draw few AA lines and save the image to a png file. I tried to find it in apple docs but there are CGImage, NSImage, CIImage and more. which one is easiest for my goal? I only need to support the latest mac os x version so new things are not a problem.

Upvotes: 0

Views: 965

Answers (2)

Mac_Cain13
Mac_Cain13

Reputation: 3633

Well your question is actually two questions in one.

First question is about how to draw an image. You should first read the docs about drawing images. Apple has a Cocoa Drawing Guide about this topic. Start from there to draw images.

Then you need to save the image to disk. Here is a nice piece of code from over here:

NSBitmapImageRep *bits = ...; // get a rep from your image, or grab from a view

NSData *data;
data = [bits representationUsingType: NSPNGFileType
             properties: nil];
[data writeToFile: @"/path/to/wherever/test.png"
      atomically: NO];

Upvotes: 1

omz
omz

Reputation: 53561

Probably the easiest way is to use an NSImage and draw directly into it after calling lockFocus.

Example:

NSSize imageSize = NSMakeSize(512, 512);
NSImage *image = [[[NSImage alloc] initWithSize:imageSize] autorelease];
[image lockFocus];
//draw a line:
[NSBezierPath strokeLineFromPoint:NSMakePoint(100, 100) toPoint:NSMakePoint(200, 200)];
//...
NSBitmapImageRep *imageRep = [[[NSBitmapImageRep alloc] initWithFocusedViewRect:NSMakeRect(0, 0, imageSize.width, imageSize.height)] autorelease];
NSData *pngData = [imageRep representationUsingType:NSPNGFileType properties:nil];
[image unlockFocus];
[pngData writeToFile:@"/path/to/your/file.png" atomically:YES];

Upvotes: 4

Related Questions