Search code examples
objective-cxcodecocoansimageclip

Clip to image mask with Cocoa


I'm trying to implement a tabbar similar to the ones in XCode 4:

enter image description here

I could implement a simple tab control with custom images, but I'd like to apply that inner shadow effect programmatically. I'd like to supply simple icons only using one color without any gradient or shadow effect, basically just the shape of the icon. Then I would paint it black, blur it and draw it. During drawing I need to clip to the original shape however. Could someone point me to the right direction/classes? I searched through Cocoa Drawing documentation but didn't find anything. Thanks!


Solution

  • NSImage has a concept of a "template image". This is a black and clear image which is suitable for various processing like inverting, embossing, engraving, etc.

    An NSImage loaded by name whose name ends with "Template" is automatically marked as a template image. Otherwise, you can mark an image as a template with -setTemplate:. You can check whether an image is a template using -isTemplate.

    An image being a template does not inherently change how the image is rendered. It's a bit of metadata that code can look at and decide to alter the way it renders the image. There isn't much documentation about how exactly that rendering should be performed. Rather, you are supposed to take advantage of the built-in support provided by NSCell, the only class in AppKit which pays attention to whether an image is a template.

    This is described in greater detail in the older AppKit release notes.

    That said, if you're still looking for making an image mask and clipping to it, you may need to drop down to Core Graphics. CGImage directly supports the notion of mask images. CGContext supports clipping to a mask image with CGContextClipToMask(). See the Quartz 2D Programming Guide.