13

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!

Lou Howard
  • 131
  • 1
  • 1
  • 3

2 Answers2

5

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

Frederik Slijkerman
  • 6,471
  • 28
  • 39
1

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

David
  • 14,205
  • 20
  • 97
  • 144
  • 3
    I'm not entirely sure if I'm using CALayer correctly, but I added the following to my initWithFrame: `[self setWantsLayer:YES];` `[self setLayer:[CALayer layer]];` `self.layer.cornerRadius = 5.0;` That doesn't seem to have any effect. – Lou Howard Apr 28 '11 at 20:33
  • Can you try it again but place `[self setWantsLayer:YES];` after the other two lines. – David Apr 28 '11 at 21:17
  • 1
    Tried swapping the lines -- still the same outcome – Lou Howard Apr 29 '11 at 03:05