刚开始做项目时,给圆角加阴影,如:
`UIImageView *image = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"leftbackiamge"]];
image.frame = CGRectMake(100, self.view.frame.size.height - 300, 100, 100);
image.layer.masksToBounds = YES;
image.layer.cornerRadius = 50;
image.layer.shadowOffset = CGSizeMake(0, 5);
image.layer.backgroundColor = [UIColor brownColor].CGColor;
image.layer.shadowColor = [UIColor brownColor].CGColor;
image.layer.shadowOpacity = 0.7;
image.layer.cornerRadius = 50;
[self.view addSubview:image];
这样写 但是出来的效果
只有圆角没有阴影
为何?
因为本身的masksToBounds方法就是超出父视图部分裁剪掉,所以加的阴影部分为超出部分,所以导致阴影显示不出来
解决方法:加一个图层,把圆角图片加到图层上
UIImageView *image = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"leftbackiamge"]];
image.frame = CGRectMake(100, self.view.frame.size.height - 300, 100, 100);
//加个图层 设置阴影
CALayer *layer = [[CALayer alloc] init];
layer.frame = CGRectMake(100, self.view.frame.size.height - 300, 100, 100);
layer.shadowOffset = CGSizeMake(0, 5);
layer.backgroundColor = [UIColor brownColor].CGColor;
layer.shadowColor = [UIColor brownColor].CGColor;
layer.shadowOpacity = 0.7;
layer.cornerRadius = 50;
[self.view.layer addSublayer:layer];
image.layer.masksToBounds = YES;
image.layer.cornerRadius = 50;
//注意一定要先上层再上image,这样保证image在层之上。
[self.view addSubview:image];
注意:必须先上层再加image,这样确保image在图层上
效果:
就成功了
下面说一下按钮的渐变颜色,一个道理把渐变的图层加到按钮图层上
//渐变的按钮
UIButton *lookBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
lookBtn.frame = CGRectMake(100, 100,100, 100);
[lookBtn setTitle:@"查看详情" forState:(UIControlStateNormal)];
[lookBtn addTarget:self action:@selector(lookBtn) forControlEvents:(UIControlEventTouchUpInside)];
lookBtn.layer.shadowColor=[TCUIColorFromRGB(0x24A7F2) colorWithAlphaComponent:0.5].CGColor;
lookBtn.layer.shadowOffset=CGSizeMake(4, 4);
lookBtn.layer.shadowOpacity=0.5;
lookBtn.layer.shadowRadius= 5;
//渐变颜色
CAGradientLayer *gradientLayer = [CAGradientLayer layer];
gradientLayer.colors = @[(__bridge id)TCUIColorFromRGB(0x5FCAFF).CGColor, (__bridge id)TCUIColorFromRGB(0x24A7F2).CGColor];
gradientLayer.locations = @[@0.3, @1.0];
gradientLayer.startPoint = CGPointMake(0, 0);
gradientLayer.endPoint = CGPointMake(1.0, 0);
gradientLayer.frame = CGRectMake(0, 0, 100, 100);
gradientLayer.cornerRadius = 50;
[lookBtn.layer addSublayer:gradientLayer];
[self.view addSubview:lookBtn];
建一个图层,保证渐变,加到按钮图层即可
此处为用到的宏定义
#define TCUIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue &0xFF00) >>8))/255.0 blue:((float)(rgbValue &0xFF))/255.0 alpha:1.0]
效果如下
代码demo地址:https://github.com/jinshuaier/shadow
如果问题,欢迎加我qq 479401910,共同学习,努力进步!