iOS UIView同时设置圆角和阴影

前言

圆角和阴影是开发中用的比较多的属性,现在几乎所有的APP都会使用这两个属性。但是在设置圆角的时候如果layer.masksToBounds = YES;那么再设置阴影就无效了。本文主要讨论下如何让二者并存。

1. 设置masksToBounds为NO

- (void)normalShadow {
    
    UIView *sv             = [UIView new];
    sv.frame               = CGRectMake(100, 100, 200, 200);
    sv.backgroundColor     = [UIColor whiteColor];
    sv.layer.cornerRadius  = 5;
    sv.layer.masksToBounds = NO;
    
    sv.layer.shadowColor   = [UIColor lightGrayColor].CGColor;
    sv.layer.shadowOffset  = CGSizeMake(0, 0);
    sv.layer.shadowOpacity = 0.8;
    sv.layer.shadowRadius  = 8;
    
    [self.view addSubview:sv];
}

2.加入一个view用来显示阴影

- (void)shadow {
    
    UIView *v1             = [UIView new];
    v1.frame               = CGRectMake(0, 0, 200, 200);
    v1.backgroundColor     = [UIColor whiteColor];
    v1.layer.cornerRadius  = 5;
    v1.layer.masksToBounds = YES;
    
    UIView *v2             = [UIView new];
    v2.layer.shadowColor   = [UIColor lightGrayColor].CGColor;
    v2.layer.shadowOffset  = CGSizeMake(0, 0);
    v2.layer.shadowOpacity = 0.8;
    v2.layer.shadowRadius  = 8;
    v2.frame               = CGRectMake(100, 100, 200, 200);
    [v2 addSubview:v1];
    
    [self.view addSubview:v2];
    
}

3.加入一个layer用来显示阴影

- (void)LayerShadow {
   CALayer *shadowLayer      = [CALayer layer];
   shadowLayer.shadowColor   = [UIColor blackColor].CGColor;
   shadowLayer.shadowOffset  = CGSizeMake(0, 0);
   shadowLayer.shadowOpacity = 1;
   shadowLayer.shadowRadius  = 10;
   shadowLayer.frame         = CGRectMake(100, 100, 200, 200);
   
   UIView *sv             = [UIView new];
   sv.frame               = CGRectMake(0, 0, 200, 200);
   sv.backgroundColor     = [UIColor whiteColor];
   sv.layer.cornerRadius  = 5;
   sv.layer.masksToBounds = YES;
   
   [self.view.layer addSublayer:shadowLayer];
   
   [shadowLayer addSublayer:sv.layer];
   
}

以上方法都可以实现圆角和阴影共存,具体使用哪种就要看自己的需求了。

你可能感兴趣的:(iOS UIView同时设置圆角和阴影)