3

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.

Jack Humphries
  • 13,056
  • 14
  • 84
  • 125

3 Answers3

5

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;
}
rezand
  • 576
  • 3
  • 11
0

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.

Wain
  • 118,658
  • 15
  • 128
  • 151
  • Check what `quartzPathFromBezierPath` returns, why don't you just ask the bezier for its path? – Wain Jun 30 '13 at 21:18
  • I don't think you can ask an `NSBezierPath` directly for a `CGPath` (even though you can for `UIBezierPath`). I found the source code for `quartzPathFromBezierPath:` on Apple's site. How would you do this though? – Jack Humphries Jul 01 '13 at 02:42
  • Ok, I misread the class name. Are you setting the view or layer to clip to bounds? – Wain Jul 01 '13 at 06:01
0

Try following this answer, Here

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

Renato Ioshida
  • 421
  • 3
  • 6