Search code examples
objective-ccocoansviewnsimage

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


Solution

  • 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.