views:

269

answers:

2

I'm trying to find out how to draw a path, and then fill it with content from an image, e.g. a .png. I have tiles of various shapes (square, triangle, etc., each defined by an NSBezierPath. I can fill them with solid color, but I also want to be able to fill them with some kind of bitmap image instead of solid color.

+1  A: 

I believe what you want is to clip the drawing in the current graphics context. Apple has good docs on this. Their code sample there works brilliantly, and is a canonical example of how to perform fairly efficient drawing in the graphics context configuring by Cocoa before your drawRect: is called.

Essentially, when your drawRect is called, whatever you end up drawing is automatically masked by the clipping path of the current graphics context (aka, the path configured with: [myBezierPath addClip]). addClip is a method specifically designed to modify the current graphics context, which is "locked" as the target of the addClip method before drawRect is called.

Jarret Hardie
A: 

Jarret's answer is probably the best option, but if you wanted to avoid messing with the graphics context, you could also use NSColor's +colorWithPatternImage: class method. This basically lets you use an image anywhere you would normally use a color.

Matt Ball
Good suggestion. Any chance you mean "NSColor +colorWithPatternImage:", though, Matt? I can't seem to find a doc reference to +colorWithImage, but I could be missing something.
Jarret Hardie
Good catch. I've fixed it in the answer. Thanks.
Matt Ball