Inner shadow in Cocoa

I've been recently playing around with custom NSView trying to achieve same look as Safari's "Add Tab" button.

After a few unsuccessful tries I've stumbled upon this question on StackOverflow which been of huge help.

The problem with code on StackOverflow is that it needs stroked border in order to work, but if make stroke white and change compositing operation to NSCompositingPlusDarker which negates any color changes by the stroke and allows us to have dark inner shadow effect on any background.

Here's complete code for custom NSView

- (BOOL)isOpaque
{
  return NO;
}

- (void)drawRect:(NSRect)dirtyRect
{
  NSGraphicsContext *context = [NSGraphicsContext currentContext];
  [context saveGraphicsState];

  [context setCompositingOperation:NSCompositePlusDarker];

  NSBezierPath *path = [NSBezierPath
    bezierPathWithRoundedRect:[self bounds]
    xRadius:2.0f
    yRadius:2.0f];

  [[NSColor whiteColor] setStroke];

  NSShadow * shadow = [[[NSShadow alloc] init] autorelease];
  [shadow setShadowColor:[NSColor colorWithCalibratedWhite:0.0f
    alpha:0.25f]];
  [shadow setShadowBlurRadius:3.0f];
  [shadow set];

  [path stroke];

  [context restoreGraphicsState];
}
Social comments Cackle