365Cocoa

A snippet of Objective-C code per day, 365 days long.
Written by Pieter Omvlee, developer and owner of Bohemian Coding.

Mar 15

Day 16: Custom drawing (5) : -addClip:

NSBezierPath is for more useful than for simply creating ovals or rectangles. You can construct your own shapes using -lineTo: and curveTo:. Don’t forget that when you build up a path, always start with a -moveTo:, otherwise you’ll get an exception. Drawing an NSBezierPath is like putting your pen on a piece of paper. Wherever you first put down the pen is the -moveTo: call. Then when you your pen in a straight line to another place, that’s a -lineTo: call. For curved lines, use -curveTo:. All of these move from the previous point to the new location thus chaining them together.

Play a bit with NSBezierPaths to get a feel for constructing them. Today’s snippet is just a method call; the -addClip: method. This is where NSBezierPath really shines. Wat -addClip: does is that any drawing outside the bezierpath will be clipped or, cut off.

The first question one will have is to choose between -addClip: and -setClip:. The answer is easily given; use -addClip:. The reason is that your view is never the first to draw; any view may add clips to the current drawing context. Your view itself for example doesn’t draw outside its bounds and I suppose that’s another clip as well. -addClip: adds to the current collection of clippings whereas -setClip: replaces them all. I believe this is the explanation but I’ve had a few cases where use of -setClip: had some weird results which were fixed by replacing it by -addClip:.

If you plan to do custom drawing, no doubt at some point you’ll find this method to be useful. One use is for making inner strokes on paths because by default NSBezierPath centers the stroke. Maybe by now you’ll know the solution to this but I’ll give it tomorrow anyway, together with a little explanation of NSGraphicsContext.


  1. 365cocoa posted this