Objective-c – Custom NSView with rounded corners and drop shadow

cocoansbezierpathnsshadownsviewobjective c

I'm trying to create a custom NSView with both rounded corners and a drop shadow. I created an NSView subclass and have the following drawRect: method

- (void)drawRect:(NSRect)dirtyRect
{
    NSRect rect = NSMakeRect([self bounds].origin.x + 3, [self bounds].origin.y + 3, [self bounds].size.width - 6, [self bounds].size.height - 6);

    NSBezierPath *path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:5.0 yRadius:5.0];
    [path addClip];

    NSShadow *shadow = [[[NSShadow alloc] init] autorelease];
    [shadow setShadowColor:[NSColor redColor]];
    [shadow setShadowBlurRadius:2.0f];
    [shadow setShadowOffset:NSMakeSize(0.f, -1.f)];
    [shadow set];

    [[NSColor controlColor] set];
    NSRectFill(rect);

    [super drawRect:dirtyRect];
}

The result is an NSView drawn with rounded corners, but no shadow (but I do see tinges of the red color around corners in the anti-aliasing). If I comment out the NSBezierPath then I will get a square NSView with a shadow. I didn't see anything in the docs to suggest that NSShadow and NSBezierPath are mutually exclusive, so I'm obviously missing something.

Any ideas are greatly appreciated!

Best Answer

It looks like the shadow doesn't respect the clipping path. Did you try [path fill] instead of NSFillRect?