使用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];
效果如下:
把 clipsToBounds 设置成 NO 试试 _coverImgView.clipsToBounds = NO;
再试试用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];
自己写了一个交换方法,给UIView添加一个背景CALayer,用这个CALayer做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.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];
再次运行:
GitHub地址:UIShadow+UIView
如有不足之处,欢迎指出🙂