views:

193

answers:

1

Hiya,

I'm trying to draw a shadow and a corner radius on an image. I can add them separately, but I've got no way to add both effects at the same time. I'm adding a shadow with:

[layer setShadowOffset:CGSizeMake(0, 3)];
[layer setShadowOpacity:0.4];
[layer setShadowRadius:3.0f];
[layer setShouldRasterize:YES];

Here, layer is a CALayer of a UIView subclass. So this works whenever I set

[layer setMasksToBounds:NO];

Now to add a corner radius I do this:

[layer setCornerRadius:7.0f];

but I need to set MasksToBounds to YES in order for this to work:

[layer setMasksToBounds:YES];

Is there anyway I can get both of these effects to add?

Thanks for your time,

Denis

A: 

Yes, yes there is...

If you want both a corner radius and a drop shadow, you don't turn on -masksToBounds, but rather set the corner radius and set the bezier path of the shadow with a rounded rect. Keep the radius of the two the same:

[layer setShadowOffset:CGSizeMake(0, 3)];
[layer setShadowOpacity:0.4];
[layer setShadowRadius:3.0f];
[layer setShouldRasterize:YES];

[layer setCornerRadius:12.0f];
[layer setShadowPath:
                   [[UIBezierPathbezierPathWithRoundedRect:[self bounds]
                                              cornerRadius:12.0f] CGPath]];

You might want to check your performance without the -shouldRasterize parameter set once you're setting the shadow path. Drawing performance tends to be very good once you've set a shadow path.

Matt Long
Thanks for that
Denis Ogun