Custom NSView with rounded corners and drop shadow
Asked Answered
F

2

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!

Fideicommissary answered 28/4, 2011 at 20:20 Comment(0)
R
5

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

Ryley answered 28/4, 2011 at 20:24 Comment(2)
I put in [path fill] in the place of NSFillRect() and the result was the sameFideicommissary
Just in case anyone read this [path fill] worked for my to draw a rounded corner rect inside drawRectAmory
H
1

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

Holophrastic answered 28/4, 2011 at 20:26 Comment(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.Fideicommissary
Can you try it again but place [self setWantsLayer:YES]; after the other two lines.Holophrastic
Tried swapping the lines -- still the same outcomeFideicommissary

© 2022 - 2024 — McMap. All rights reserved.