1

I am trying to add a shadow to a NSImageView on an MAC application.

I created a custom NSImageView class "ShadowView.h" and modified the drawRect: like so:

- (void)drawRect:(NSRect)dirtyRect {
    [super drawRect:dirtyRect];

    NSShadow *shadow = [[NSShadow alloc] init];
    [shadow setShadowBlurRadius:5];
    [shadow setShadowOffset:NSMakeSize(30.0, 3.0)];
    [shadow setShadowColor:[NSColor redColor]];
    [shadow set];

    [self setWantsLayer:YES];
    [self setShadow:shadow];
}

However nothing happens. Also, when I debug I can see the above code being called. I looked at this question from 5 years ago but it seems to not work anymore

Adding a Shadow to a NSImageView

Thank you!

Community
  • 1
  • 1
  • Does your view's superview also have layer-backing enabled? I built a quick test app with this code, and unless the superview _also_ has layer backing, the shadow gets clipped at the edge of the view bounds. Perhaps there is a shadow, but it's outside your image view, and the superview doesn't have a layer? – Cocoatype Aug 14 '16 at 01:59
  • Also, and this might be a stupid question, do you have an image in the image view? The shadow for an `NSImageView` is calculated based on the image's alpha, so if there's no image, there's no shadow. – Cocoatype Aug 14 '16 at 02:03
  • @Arclite The issue was that my superview did not have layer-backing enabled! I just added [self.view wantsLayer:YES] to my viewController viewDidLoad. If you make it an answer I can accept it as correct. Thank you. – Leonardo Murri Aug 14 '16 at 13:18
  • Done! Glad I could help. – Cocoatype Aug 14 '16 at 13:36

2 Answers2

1

When adding a shadow to a view, that view's superview also needs to have layer-backing enabled. If it doesn't, the view's shadow gets clipped at its own bounds, as seen in this sample app:

clipped shadow

Make sure you call -setWantsLayer:YES on your view's superview (or check the "Core Animation Layer" checkbox in Interface Builder) in order to make sure the shadow is completely visible:

full shadow

Cocoatype
  • 2,572
  • 25
  • 42
0

You should set these somewhere else like, initWithFrame: take them out of the drawRect:

[self setWantsLayer:YES];
[self setShadow:shadow];
Tolga Katas
  • 365
  • 1
  • 6