iOS圆角和阴影并存的两种实现方法

版权声明:本文为陈云峰(www.swifty.cc)原创文章,未经允许不得转载。 https://blog.csdn.net/feosun/article/details/86657330

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

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.

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

那么我们怎么实现呢?

实现方法一:添加一个上层的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];

实现方法二:添加一个Subview

  1. 在subview上面设置圆角,把subview的masksToBounds属性设置为true
  2. 在parent view上面设置阴影,把parent view的masksToBounds属性设置为false,并设置parent view的cornerRadius和subview一样,就可以了。

不知道你看懂了没有呢,如果有问题欢迎留言~

猜你喜欢

转载自blog.csdn.net/feosun/article/details/86657330