Custom NSThemeFrame
After seeing Safari 4 drawing its tab bar in a custom way, I wondered how to do that. Each window has a frame view (the superview
ofcontentView
) that draws the window, replacing that view's drawRect:
with our own will let us draw it ourselves !
First, replace the window's frame drawRect:
with our own :
// Get window's frame view class id class = [[[window contentView] superview] class]; // Add our drawRect: to the frame class Method m0 = class_getInstanceMethod([self class], @selector(drawRect:)); class_addMethod(class, @selector(drawRectOriginal:), method_getImplementation(m0), method_getTypeEncoding(m0)); // Exchange methods Method m1 = class_getInstanceMethod(class, @selector(drawRect:)); Method m2 = class_getInstanceMethod(class, @selector(drawRectOriginal:)); method_exchangeImplementations(m1, m2);
Cocoa will then call our method each time the window frame needs to be drawn. We can draw an entirely custom frame or draw over the existing one. (The attached sample does the latter)
A standard Cocoa window has rounded corners that need to be accounted for by building a clipping path to clip our custom drawing to the window shape :
- Get the rounded corner radius with
roundedCornerRadius
- Using this radius, build a rounded corner path that describes the window
- Intersect that path with the current
rect
- Draw our stuff
- (void)drawRect:(NSRect)rect { // Call original drawing method [self drawRectOriginal:rect]; // // Build clipping path : intersection of frame clip (bezier path with rounded corners) and rect argument // NSRect windowRect = [[self window] frame]; windowRect.origin = NSMakePoint(0, 0); float cornerRadius = [self roundedCornerRadius]; [[NSBezierPath bezierPathWithRoundedRect:windowRect xRadius:cornerRadius yRadius:cornerRadius] addClip]; [[NSBezierPath bezierPathWithRect:rect] addClip]; // Any custom drawing goes here ... }Sample Code

NSImageNameActionTemplate
image and a custom color (in
kCGBlendModeColorDodge
) over the existing frame