user523791
user523791

Reputation: 69

Draw a NSImage using cocoa

Currently I am drawing some shapes using Bézier Paths on an NSView. Where the drawing code get execute on drawRect: method and creates an image in the end.

I don't want to show this View to the user anywhere. However as I know the drawRect: method only gets called when we add the view to a superview and thereafter calling display or displayNeedsUpdate methods on NSView.

My requirement is to create an image of my required drawing.

Rather than drawing on to a NSView and converting it to a PNG , Is there any way we can draw the image directly ?

Upvotes: 2

Views: 1421

Answers (1)

Jean
Jean

Reputation: 7673

You have to create an NSBitmapImageRep and use bitmapImageRepForCachingDisplayInRect: by specifying your views frame.

The bitmap image representation will be drawn.

Then, you only need to use representationUsingType:NSPNGFileType properties:nil and write the result in a file.

The sample below is extracted from cocoa with love's tutorial: Advanced drawing using AppKit

NSRect iconViewFrame = iconView.frame;
[iconView setFrame:[iconView nativeRect]];

NSBitmapImageRep *bitmapImageRep =
    [iconView bitmapImageRepForCachingDisplayInRect:[iconView frame]];
[iconView
    cacheDisplayInRect:[iconView bounds]
    toBitmapImageRep:bitmapImageRep];
[[bitmapImageRep representationUsingType:NSPNGFileType properties:nil]
    writeToURL:[savePanel URL]
    atomically:YES];

[iconView setFrame:iconViewFrame];

They also advise:

Creating your own NSBitmapImageRep, setting the NSGraphicsContext using graphicsContextWithBitmapImageRep:, locking focus yourself and invoking drawRect: directly will avoid these issues and is more flexible. But it would have been more work so I didn't bother for this sample project (I mostly put this export code into the app so I could create the app's icon).

So you may choose the best-suited solution for your needs.

Upvotes: 2

Related Questions