iOS 圆角和阴影并存的方法

前提

圆角和阴影无法共存的原因就是因为这句代码。

Because shadow is an effect done outside the View, and that masksToBounds set to YES will tell the UIView not to draw everything that is outside itself.

这句话的意思就是,圆角都是我给你割出来的,圆角外面的阴影自然也割掉了~ 所以,这么看来,圆角与阴影不能并存啊(仅限这种圆角实现的方式)

处理方式

  1. 在下面再加一个subView负责处理圆角,而父类view处理阴影
    父类View:
    NSInteger standard = 1;
    parentView.layer.cornerRadius = 10*standard;
    parentView.layer.shadowColor = [UIColor darkGrayColor].CGColor;
    // 设置阴影偏移量
    parentView.layer.shadowOffset = CGSizeMake(3*standard,3*standard);
    // 设置阴影透明度
    parentView.layer.shadowOpacity = 1;
    // 设置阴影半径
    parentView.layer.shadowRadius = 3* standard;
    parentView.layer.masksToBounds = NO;

subView:

    NSInteger standard = 1;
    subView.layer.cornerRadius = 10*standard;
    subView.layer.masksToBounds = YES;

注意父类View的masksToBounds=NO cornerRadius等于subView的大小 suvBiew的masksToBounds=YES

  1. 添加一个上层Layer:
 CALayer *subLayer=[CALayer layer]; 
CGRect fixframe = _tableView.frame; 
subLayer.frame= fixframe; 
subLayer.cornerRadius=8; 
subLayer.backgroundColor=[[UIColor blackColor] colorWithAlphaComponent:0.8].CGColor; 
subLayer.masksToBounds=NO; 
subLayer.shadowColor = [UIColor blackColor].CGColor;//shadowColor阴影颜色 
subLayer.shadowOffset = CGSizeMake(3,2);//shadowOffset阴影偏移,x向右偏移3,y向下偏移2,默认(0, -3),这个跟shadowRadius配合使用 
subLayer.shadowOpacity = 0.8;//阴影透明度,默认0 
subLayer.shadowRadius = 4;//阴影半径,默认3 
[self.bkgView.layer insertSublayer:subLayer below:_tableView.layer]; 
- (void)drawRect:(CGRect)rect {
    CGContextRef ref = UIGraphicsGetCurrentContext();
    CGContextMoveToPoint(ref, self.bounds.origin.x+10, 0); // 起点
    CGContextAddLineToPoint(ref, self.bounds.origin.x, 10); // 连线
    CGContextAddLineToPoint(ref, 20, 10); // 连线
    CGContextClosePath(ref); // 闭拢
    [THEME_COLOR setFill];// 背景填充颜色
    [THEME_COLOR setStroke]; // 连线颜色 即边框颜色
    CGContextDrawPath(ref, kCGPathFillStroke);
}

参考
https://blog.csdn.net/feosun/article/details/86657330
https://www.jianshu.com/p/0be78fc8022d

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容