Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom NSView with rounded corners and drop shadow

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!

like image 642
Lou Howard Avatar asked Apr 28 '11 20:04

Lou Howard


2 Answers

You can use the CALayer's cornerRadius method to get the rounded corner effect.

like image 123
David Avatar answered Oct 25 '22 07:10

David


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

like image 30
Frederik Slijkerman Avatar answered Oct 25 '22 08:10

Frederik Slijkerman