How to add shadow to NSView

4.6k Views Asked by At

I've spent some time trying to figure out how to add a shadow to an NSView. For now, I am attempting to use the NSShadow class to accomplish this. My code is below. I am attempting to create the shadow in a custom init method in a NSView subclass. No matter what I try, no shadow appears.

NSShadow *dropShadow = [[NSShadow alloc] init];
[dropShadow setShadowColor:[NSColor blackColor]];

[self setWantsLayer:YES];
[self setShadow:dropShadow];

Edit

Here is how I tried to do it with CALayer.

self.layer.shadowOffset = CGSizeMake(10, 10);
self.layer.shadowOpacity = 1.0;
self.layer.shadowRadius = 10.0;
self.layer.shadowPath = [self quartzPathFromBezierPath:[NSBezierPath bezierPathWithRect:frame]];

quartzPathFromBezierPath: converts an NSBezierPath to a CGPath.

3

There are 3 best solutions below

0
rezand On

use this with offset and other params need to be set

- (id)initWithFrame:(NSRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
    NSShadow *dropShadow = [[NSShadow alloc] init];
    [dropShadow setShadowColor:[NSColor redColor]];
    [dropShadow setShadowOffset:NSMakeSize(0, -10.0)];
    [dropShadow setShadowBlurRadius:10.0];

    [self setWantsLayer: YES];
    [self setShadow: dropShadow];

    [dropShadow release];
}

return self;
}
3
Wain On

An alternative to NSShadow is to get the views layer and use its shadow related properties. In particular, be sure to set the shadowOpacity to something above 0 (the default).

Note that you can't use the shadow offset and the shadow path at the same time.

0
Renato Ioshida On

Try following this answer, Here

I think the most important line is the self.view.superview?.wantsLayer = true