iOS-设置阴影和圆角效果

参考链接:视觉效果和变换

iOS 给一个设置过圆角的View添加阴影效果

1.圆角效果

wechatBt.layer.cornerRadius = 8;
wechatBt.layer.masksToBounds = YES;//超出父视图部分不显示。


2.阴影效果

messageBt.layer.shadowOffset = CGSizeMake(1, 1);
messageBt.layer.shadowOpacity = 0.8;
messageBt.layer.shadowColor = [UIColor blackColor].CGColor;


3.圆角加阴影效果(此方法错误)

messageBt.layer.cornerRadius = 8;
//messageBt.layer.masksToBounds = NO;//此处不可以设置YES,否则阴影效果无法实现,但是设置为NO时,圆角无法实现。
messageBt.layer.shadowOffset = CGSizeMake(1, 1);
messageBt.layer.shadowOpacity = 0.8;
messageBt.layer.shadowColor = [UIColor blackColor].CGColor;

 

解决方法:

创建一个view,设置阴影效果,然后将所需视图添加到view中,设置圆角效果即可。

UIView *shadowView = [[UIView alloc]initWithFrame:CGRectMake(60, 60, 100, 100)];
    shadowView.backgroundColor = UIColor.blueColor;
    shadowView.userInteractionEnabled = YES;
    shadowView.layer.cornerRadius = 50;
    shadowView.layer.shadowOffset = CGSizeMake(1, 5);
    shadowView.layer.shadowOpacity = 0.8;
    shadowView.layer.shadowColor = [UIColor lightGrayColor].CGColor;
    //shadowView.layer.masksToBounds = NO;
    [self.view addSubview:shadowView];
    
    UIButton *messageBt = [UIButton buttonWithType:UIButtonTypeSystem];
    [messageBt setFrame:CGRectMake(0, 0, 100, 100)];
    [messageBt setBackgroundColor:UIColor.cyanColor];
    [messageBt setTitle:@"button" forState:UIControlStateNormal];
    messageBt.layer.cornerRadius = 50;
    messageBt.layer.masksToBounds = YES;
    [shadowView addSubview: messageBt];

Demo地址:https://github.com/cxymq/ShadowAndRadius

你可能感兴趣的:(iOS开发小结)