变更记录
序号 | 录入时间 | 录入人 | 备注 |
---|---|---|---|
1 | 2016-03-08 | Alfred Jiang | - |
1 | 2017-01-20 | Alfred Jiang | 更新 CAGradientLayer 设置四周阴影的效果示例 |
方案名称
UIView - 代码设置 UIView 的阴影、圆角、边框效果
关键字
UIView \ 圆角 \ 阴影 \ 边框 \ CAGradientLayer
需求场景
- 需要为 UIView 等控件设置圆角、阴影、边框效果时
参考链接
- 简书 - iOS给UIview 加阴影加圆角加边框
- CSDN - iPhone之为UIView设置阴影(CALayer的shadowColor,shadowOffset,shadowOpacity,shadowRadius,shadowPath属性)
详细内容
1. 导入 #import
2. 设置阴影
myview.layer.shadowOpacity = 0.5;// 阴影透明度
myview.layer.shadowColor = [UIColor grayColor].CGColor;// 阴影的颜色
myview.layer.shadowRadius = 3;// 阴影扩散的范围控制
myview.layer.shadowOffset = CGSizeMake(1, 1);// 阴影的范围
通过 CAGradientLayer 设置四周阴影的效果示例
- (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. 设置圆角
myview.layer.cornerRadius = 8;
myview.layer.masksToBounds = YES;
注意,UILabel 控件需要额外设置 clipsToBounds = YES 才可以实现圆角效果
mylabel.layer.clipsToBounds = YES;
4. 设置边框
myview.layer.borderWidth = 8;
myview.layer.borderColor =[[UIColor grayColor] CGColor];
效果图
(无)