iOS UIView设置阴影效果

做iOS开发的都会知道,给一个视图设置圆角只需要设置layer.cornerRadius,并masksToBounds值为YES即可,但若还想设置阴影效果,发现圆角和阴影是不兼容的,这里提供两种方法同时设置圆角和阴影
①父视图阴影,子视图圆角

    UIView *shadowView = [[UIView alloc]initWithFrame:CGRectMake(100, 100, 200, 200)];
    [self.view addSubview:shadowView];
    
    shadowView.layer.shadowColor = [UIColor blackColor].CGColor;
    shadowView.layer.shadowOffset = CGSizeMake(0, 0);
    shadowView.layer.shadowOpacity = 0.8;
    shadowView.layer.shadowRadius = 9.0;
    shadowView.layer.cornerRadius = 9.0;

    UILabel *label = [[UILabel alloc] initWithFrame:shadowView.bounds];
    label.backgroundColor =[UIColor redColor];
    label.layer.cornerRadius = 10;
    label.layer.masksToBounds = YES;
    [shadowView addSubview:label];

②高效的使用shadowPath

    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(100, 400, 200, 200)];
    view.backgroundColor = [UIColor redColor];
    view.layer.shadowColor = [UIColor blackColor].CGColor;//阴影颜色
    view.layer.shadowOpacity = 0.8;//阴影透明度,默认为0,如果不设置的话看不到阴影,切记,这是个大坑
    view.layer.shadowOffset = CGSizeMake(0, 0);//设置偏移量
    view.layer.cornerRadius = 9.0;
    view.layer.shadowRadius = 9.0;
    [self.view addSubview:view];
    
    //参数依次为大小,设置四个角圆角状态,圆角曲度
    view.layer.shadowPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:5 cornerRadii:CGSizeMake(0, 0)].CGPath;

效果图如下


阴影

你可能感兴趣的:(iOS UIView设置阴影效果)