变更记录

序号 录入时间 录入人 备注
1 2016-03-08 Alfred Jiang -
1 2017-01-20 Alfred Jiang 更新 CAGradientLayer 设置四周阴影的效果示例

方案名称

UIView - 代码设置 UIView 的阴影、圆角、边框效果

关键字

UIView \ 圆角 \ 阴影 \ 边框 \ CAGradientLayer

需求场景

  1. 需要为 UIView 等控件设置圆角、阴影、边框效果时

参考链接

  1. 简书 - iOS给UIview 加阴影加圆角加边框
  2. CSDN - iPhone之为UIView设置阴影(CALayer的shadowColor,shadowOffset,shadowOpacity,shadowRadius,shadowPath属性)

详细内容

1. 导入 #import <QuartzCore/QuartzCore>
2. 设置阴影
1
2
3
4
myview.layer.shadowOpacity = 0.5;// 阴影透明度
myview.layer.shadowColor = [UIColor grayColor].CGColor;// 阴影的颜色
myview.layer.shadowRadius = 3;// 阴影扩散的范围控制
myview.layer.shadowOffset = CGSizeMake(1, 1);// 阴影的范围

通过 CAGradientLayer 设置四周阴影的效果示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
- (void)addTopShadow{
CAGradientLayer *shadow = [CAGradientLayer layer];
shadow.shadowColor = [UIColor blackColor].CGColor;
UIBezierPath *shadowPath = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, self.frame.size.width, 8)];
shadow.shadowPath = shadowPath.CGPath;
shadow.shadowOffset = CGSizeMake(0, -8);
shadow.shadowOpacity = 0.15;
[self.layer insertSublayer:shadow atIndex:0];
}

- (void)addLeftShadow{
CAGradientLayer *shadow = [CAGradientLayer layer];
shadow.shadowColor = [UIColor blackColor].CGColor;
UIBezierPath *shadowPath = [UIBezierPath bezierPathWithRect:CGRectMake(-8, 0, 8, self.frame.size.height)];
shadow.shadowPath = shadowPath.CGPath;
shadow.shadowOffset = CGSizeMake(0, -8);
shadow.shadowOpacity = 0.15;
[self.layer insertSublayer:shadow atIndex:0];
}

- (void)addRightShadow{
CAGradientLayer *shadow = [CAGradientLayer layer];
shadow.shadowColor = [UIColor blackColor].CGColor;
UIBezierPath *shadowPath = [UIBezierPath bezierPathWithRect:CGRectMake(self.frame.size.width, 0, 8, self.frame.size.height)];
shadow.shadowPath = shadowPath.CGPath;
shadow.shadowOffset = CGSizeMake(0, -8);
shadow.shadowOpacity = 0.15;
[self.layer insertSublayer:shadow atIndex:0];
}

- (void)addBottomShadow{
CAGradientLayer *shadow = [CAGradientLayer layer];
shadow.shadowColor = [UIColor blackColor].CGColor;
UIBezierPath *shadowPath = [UIBezierPath bezierPathWithRect:CGRectMake(0, self.frame.size.height, self.frame.size.width, 4)];
shadow.shadowPath = shadowPath.CGPath;
shadow.shadowOffset = CGSizeMake(0, 4);
shadow.shadowOpacity = 0.15;
[self.layer insertSublayer:shadow atIndex:0];
}

3. 设置圆角
1
2
myview.layer.cornerRadius = 8;
myview.layer.masksToBounds = YES;

注意,UILabel 控件需要额外设置 clipsToBounds = YES 才可以实现圆角效果

1
mylabel.layer.clipsToBounds = YES;
4. 设置边框
1
2
myview.layer.borderWidth = 8;
myview.layer.borderColor =[[UIColor grayColor] CGColor];

效果图

(无)

备注