views:

129

answers:

2

This is stumping me. I have a UIView (call it "parent"). The bottommost subview of that view is a UIImageView (call it "child"), whose frame occupies the entirety of the "parent" bounds.

I want to round the corners on the "parent" view, and set a drop shadow. I do this on the CALayer of "parent" as usual:

[[parent layer] setShadowOffset:CGSizeMake(5, 5)];
[[parent layer] setShadowRadius:6];
[[parent layer] setShadowOpacity:0.4];    
[[parent layer] setCornerRadius:6];

This shows the shadow correctly, but does not round the corners.

Here's the kicker:

  1. If I remove the "child" image view, or shrink it so it doesn't occupy the whole bounds of the "parent" view, I get the rounded corners and shadow correctly on the parent.
  2. If I leave the "child" alone but set "clipsToBounds" on the "parent" view, I get the corners correctly. But now the shadow's gone.
  3. Setting the corner radius on the layer of the child as well seems to have no effect.

It seems like the "child" image view is just obscuring the rounded corners on the "parent" view since it takes up the whole rect, and clipping based on the parent view gets the corners but also masks off the shadow. Not sure why #3 doesn't work.

What am I missing? Have I been overlooking something obvious by staring at this too long?

Thanks.

(Shockingly, the tag "roundedcorners-dropshadow" already exists. Awesome.)

A: 

Normally you have to set clipsToBounds to have rounded corners, but since you want to retain the shadow you have to round the corners of the shadow as well. Have you tried setting the shadow path using a bezier path? Keep clipsToBounds/masksToBounds to the default, NO. Something like:

  [[parent layer] setCornerRadius:6.0f];
  [[parent layer] setShadowPath:
             [[UIBezierPath bezierPathWithRoundedRect:[parent bounds] 
                   cornerRadius:6.0f] CGPath]];
Matt Long
Thanks Matt. Yes-- the rounding of the shadow corners isn't a problem-- they work whether I set it with a path or with the regular properties. I just can't get the shadow to show up at all when I set clipsToBounds, and if I don't set it, the image view kills the rounded corners. (Note that if I don't have the "child" image view at all, both work as expected)
quixoto
What happens if instead of using an image view you just set your layer's contents to the image you want? e.g. [layer setContents:(id)[image CGImage]]; You can setContentsGravity:kCAGravityResizeAspectFill to get the image to fill in the layer with aspect fill or try other constants there if that's not the desired effect.
Matt Long
A: 

Have you tried setting the bounds of the child UIImageView so that it also has rounded corners? Perhaps then it wouldn't override the shadow of the container view. Just a thought, not sure if it will work.

fogelbaby
Yes. As mentioned in point #3 above.
quixoto