Question

I want to do some custom drawing in a NSView subclass where should I get started?

Was it helpful?

Solution

As Jarret mentioned the Apple docs are a great place to start. However, some things to bear in mind:

The default coordinate system used with views is the Cartesian coordinate system where the origin is in the bottom left corner of the view. Most often you want the origin to be in the top left corner of the view so this is where you override the isFlipped: method (the default implementation which returns NO), returning YES:

- (BOOL)isFlipped
{
    return YES;
}

This "flips" the coordinate system so that the origin becomes in the top left corner, after a vertical flip has taken place. This can make some drawing position calculations easier.

The main things you'll probably want to get started with are things such as:

  • Filling basic rectangles (using the NSBezierPath class method fillRect:, along with the NSColor class for setting and using colours).
  • Working with images (using the NSImage class and the drawing methods it provides).
  • Paths, where you can draw lines and other shapes (with the NSBezierPath class).

You'll also want to take a look into Graphics Contexts at some point, and working with setting attributes (such as the current colour, a shadow etc) on them, used for subsequent drawing operations.

Probably not of immediate concern, but just a side note, that at some point you should take a look at the Optimizing View Drawing section of the View Programming Guide for Cocoa. Drawing operations should be fast, and it amazes me sometimes how little consideration people put into the performance aspects of drawing, when there are some basic things you can do to make your drawing – and therefore application – more efficient, such as only redrawing parts of the view that have actually changed, rather than the entire thing.

OTHER TIPS

Apple's Introduction to Cocoa Drawing Guide is the best place to start. Lots of examples there.

You should start at the beginning.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top