UIView设置阴影

2019-01-11  本文已影响15人  爱吃萝卜的小蘑菇

PS:

clipsToBounds
是指视图上的子视图,如果超出父视图的部分就截取掉
masksToBounds
却是指视图的图层上的子图层,如果超出父图层的部分就截取掉
如果View没有圆角或View圆角位置上没有别的控件可以直接设置:
shadowOffset = CGSizeMake(10, 10)
    self.shadowView.layer.shadowColor = [UIColor redColor].CGColor;
//    阴影偏移量
    self.shadowView.layer.shadowOffset = CGSizeMake(10, 10);
//    阴影透明度
    self.shadowView.layer.shadowOpacity = 1;
//    阴影半径
    self.shadowView.layer.shadowRadius = 5;
shadowOffset = CGSizeMake(0, 0)
shadowOffset = CGSizeMake(0, 0) 圆角
    self.shadowView.layer.shadowColor = [UIColor redColor].CGColor;
//    阴影偏移量
    self.shadowView.layer.shadowOffset = CGSizeMake(0, 0);
//    阴影透明度
    self.shadowView.layer.shadowOpacity = 1;
//    阴影半径
    self.shadowView.layer.shadowRadius = 5;
    self.shadowView.layer.cornerRadius = 10;
    
    self.shadowView.layer.shadowColor = [UIColor redColor].CGColor;
//    阴影偏移量
    self.shadowView.layer.shadowOffset = CGSizeMake(0, 5);
//    阴影透明度
    self.shadowView.layer.shadowOpacity = 1;
//    阴影半径
    self.shadowView.layer.shadowRadius = 0;

如果圆角位置有别的控件的话,需要设置masksToBounds,则需要创建一个新的layer层:

设置masksToBounds后简单方法的效果
self.shadowView.layer.cornerRadius = 10;
    self.shadowView.clipsToBounds = YES;
    
    CALayer *shadowLayer0 = [[CALayer alloc] init];
    shadowLayer0.shadowColor = [UIColor redColor].CGColor;
    shadowLayer0.shadowOpacity = 1;
    shadowLayer0.shadowOffset = CGSizeMake(0, 5);
    shadowLayer0.shadowRadius = 5;
    CGFloat shadowSize0 = 0;
    CGRect shadowSpreadRect0 = CGRectMake(-shadowSize0, -shadowSize0, self.shadowView.bounds.size.width+shadowSize0*2, self.shadowView.bounds.size.height+shadowSize0*2);
    CGFloat shadowSpreadRadius0 =  self.shadowView.layer.cornerRadius == 0 ? 0 : self.shadowView.layer.cornerRadius+shadowSize0;
    UIBezierPath *shadowPath0 = [UIBezierPath bezierPathWithRoundedRect:shadowSpreadRect0 cornerRadius:shadowSpreadRadius0];
    shadowLayer0.shadowPath = shadowPath0.CGPath;
    //重要
    shadowLayer0.frame = self.shadowView.frame;
    [self.shadowView.superview.layer insertSublayer:shadowLayer0 below:self.shadowView.layer];
添加shadowLayer的效果

注意shadowLayer要插入到View的super上

[self.shadowView.superview.layer insertSublayer:shadowLayer0 below:self.shadowView.layer];

否则就是如下效果


[self.shadowView.layer addSublayer:shadowLayer0];
上一篇 下一篇

猜你喜欢

热点阅读