CALayer 添加圆角阴影

使用pod

pod 'UIShadow+UIView'

iOS开发中给一张图片或者一个UIView 添加圆角的同时再设置阴影,阴影会无法显示的,如:

_coverImgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"cover.jpg"]];
_coverImgView.bounds = CGRectMake(0, 0, 240, 320);
_coverImgView.center = CGPointMake(CGRectGetWidth(self.view.frame) / 2, CGRectGetHeight(self.view.frame) / 2);
_coverImgView.clipsToBounds = YES;
_coverImgView.layer.cornerRadius = 6.0;
_coverImgView.layer.shadowColor = [UIColor redColor].CGColor;
_coverImgView.layer.shadowOffset = CGSizeZero;
_coverImgView.layer.shadowRadius = 5.0;
_coverImgView.layer.shadowOpacity = 1.0;
[self.view addSubview:_coverImgView];

效果如下:


Simulator Screen Shot - iPhone Xs - 2019-06-11 at 15.15.09.png

clipsToBounds 设置成 NO 试试 _coverImgView.clipsToBounds = NO;

Simulator Screen Shot - iPhone Xs - 2019-06-11 at 15.18.04.png

再试试用CALayer做一个带阴影的圆角

CALayer *layer = [CALayer layer];
layer.bounds = CGRectMake(0, 0, 240, 320);
layer.position = CGPointMake(CGRectGetWidth(self.view.frame) / 2, CGRectGetHeight(self.view.frame) / 2);
layer.cornerRadius = 6.0;
layer.backgroundColor = [UIColor whiteColor].CGColor;
layer.shadowColor = [UIColor redColor].CGColor;
layer.shadowOffset = CGSizeZero;
layer.shadowRadius = 5.0;
layer.shadowOpacity = 1.0;
[self.view.layer addSublayer:layer];
Simulator Screen Shot - iPhone Xs - 2019-06-11 at 15.23.34.png

自己写了一个交换方法,给UIView添加一个背景CALayer,用这个CALayerUIView的阴影

_coverImgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"cover.jpg"]];
_coverImgView.bounds = CGRectMake(0, 0, 240, 320);
_coverImgView.center = CGPointMake(CGRectGetWidth(self.view.frame) / 2, CGRectGetHeight(self.view.frame) / 2);
_coverImgView.shadow_opacity = 1.0;
_coverImgView.shadow_color = [UIColor redColor];
_coverImgView.shadow_offset = CGSizeZero;
_coverImgView.shadow_radius = 3.0;
_coverImgView.shadow_corner_radius = 6.0;
_coverImgView.showShadowLayer = YES;
[self.view addSubview:_coverImgView];
    
//    or use below function
//    [_coverImgView showDefaultShadow];

再次运行:


Simulator Screen Shot - iPhone Xs - 2019-06-11 at 15.28.20.png

GitHub地址:UIShadow+UIView
如有不足之处,欢迎指出

你可能感兴趣的:(CALayer 添加圆角阴影)