Lennart
Lennart

Reputation: 1560

cocoa - draw image in NSView

I'm having difficulties understanding why the below code doesn't work, what I want to achieve is an image being displayed in the top left corner of a NSView, but nothing is showing...

NSImage *map0 = [NSImage imageNamed:@"map0.png"];
NSRect rect = NSMakeRect(0, 0, 400, 400);
[map0 drawInRect:rect fromRect:NSZeroRect operation:NSCompositeSourceAtop fraction:1.0f];
[map drawRect:rect];

EDIT:

map is the NSView into which I would like to draw the image into

Upvotes: 0

Views: 2037

Answers (1)

Rob Napier
Rob Napier

Reputation: 299575

You never call drawRect: directly. This routine has various pre-conditions that are provided by Cocoa, such as the creation of a CGContextRef. You implement drawRect:. Cocoa calls it.

Your drawInRect:fromRect:operation:fraction: call should be put into the drawRect: of map, which should be a subclass of NSView. This specific problem is usually better solved with an NSImageView rather than a custom NSView, but if the drawing is more complex, then a custom NSView is appropriate.

Upvotes: 2

Related Questions