views:

159

answers:

3

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

A: 

You should start at the beginning.

Azeem.Butt
+4  A: 

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

Jarret Hardie
+4  A: 

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.

Perspx
Thanks you so much!
nanochrome
“Most often”? I beg to differ; in most custom views I've drawn, unflipped has worked just fine. And I don't buy that it makes “some drawing position calculations easier”; all it may do is turn some additions into subtractions or positive numbers into negative ones, and vice versa.
Peter Hosey
I guess it's down to personal opinion – but I usually find working in flipped views easier.
Perspx
I agree with Peter. Most of the non-iPhone drawing code you will find out there assumes the default Quartz coordinate space, not a flipped one. In fact, in the Core Plot library, we chose to flip the iPhone UIView coordinate space, not the Mac's, so that we could maintain an identical drawing code base between the two platforms. It's a more familiar coordinate system to experienced Cocoa developers. In any case, it's trivial to flip things around.
Brad Larson