How to use Quartz 2D to add drop shadow to an UIIm

2019-02-03 23:36发布

问题:

How do I use Quartz 2D to add drop shadow to an UIImage or UIImageView ?

Any code samples?

回答1:

imageView.layer.shadowColor = [UIColor blackColor].CGColor;
imageView.layer.shadowOffset = CGSizeMake(0, 1);
imageView.layer.shadowOpacity = 1;
imageView.layer.shadowRadius = 1.0;

Don't forget to #import <QuartzCore/QuartzCore.h> in your implementation.

EDIT:

Adding in @Luke's comment:

Just a little gotcha that might save some other people some time make sure you have not set layer.masksToBounds to YES on your view otherwise the shadow will not appear.



回答2:

+ (void)addShadowToView:(UIView*)view Color:(UIColor*)color ShadowOffset:(CGSize)offset Radius:(float)radius Opacity:(float)opacity
{
    view.layer.shadowColor = [color CGColor];
    view.layer.shadowOffset = offset;
    view.layer.shadowRadius = radius;
    view.layer.shadowOpacity = opacity;
}

Use:

[calssName addShadowToView:self.navigationController.navigationBar Color:[UIColor blackColor] ShadowOffset:CGSizeMake(1.0f, 0.5f) Radius:1.0 Opacity:0.5];