Swift版
/// 添加圆角和阴影 radius:圆角半径 shadowOpacity: 阴影透明度 (0-1) shadowColor: 阴影颜色
func addRoundedOrShadow(radius:CGFloat, shadowOpacity:CGFloat, shadowColor:UIColor) {
self.layer.cornerRadius = radius
self.layer.masksToBounds = true
let subLayer = CALayer()
let fixframe = self.frame
let newFrame = CGRect(x: fixframe.minX-(375-UIScreen.main.bounds.size.width)/2, y: fixframe.minY, width: fixframe.width, height: fixframe.height) // 修正偏差
subLayer.frame = newFrame
subLayer.cornerRadius = radius
subLayer.backgroundColor = UIColor.white.cgColor
subLayer.masksToBounds = false
subLayer.shadowColor = shadowColor.cgColor // 阴影颜色
subLayer.shadowOffset = CGSize(width: 0, height: 0) // 阴影偏移,width:向右偏移3,height:向下偏移2,默认(0, -3),这个跟shadowRadius配合使用
subLayer.shadowOpacity = Float(shadowOpacity) //阴影透明度
subLayer.shadowRadius = 5;//阴影半径,默认3
self.superview?.layer.insertSublayer(subLayer, below: self.layer)
}
经过测试添加的CALayer会偏移一点 不知道是啥问题 需要修正
let fixframe = self.frame
let newFrame = CGRect(x: fixframe.minX-(375-UIScreen.main.bounds.size.width)/2, y: fixframe.minY, width: fixframe.width, height: fixframe.height)
subLayer.frame = newFrame
OC版
/* 添加圆角和阴影
shadowOpacity: 阴影透明度
shadowColor: 阴影颜色
radius:圆角半径
*/
- (void)addProjectionWithShadowOpacity:(CGFloat)shadowOpacity shadowColor:(UIColor *)shadowColor radius:(CGFloat)radius{
self.layer.cornerRadius = radius;
self.layer.masksToBounds = YES;
CALayer *subLayer=[CALayer layer];
CGRect fixframe = self.frame;
subLayer.frame = fixframe;
subLayer.cornerRadius = radius;
subLayer.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.8].CGColor;
subLayer.masksToBounds = NO;
subLayer.shadowColor = shadowColor.CGColor;//shadowColor阴影颜色
subLayer.shadowOffset = CGSizeMake(3,3);//shadowOffset阴影偏移, width:向右偏移3,height:向下偏移3,默认(0, -3),这个跟shadowRadius配合使用
subLayer.shadowOpacity = shadowOpacity;//阴影透明度
subLayer.shadowRadius = 3;//阴影半径,默认3
[self.superview.layer insertSublayer:subLayer below:self.layer];
}
修改版
注意:
1.使用此方法 添加圆角与阴影View之上不能出现其他View将其遮盖(因为self.layer.masksToBounds = false)不能进行多余部分裁剪 故有遮盖会将圆角遮盖
2.self.layer.masksToBounds = true 阴影会被裁剪掉
func addShadow(shadowOpacity:Float, shadowColor:UIColor, radius:CGFloat) {
self.layer.shadowColor = shadowColor.cgColor
self.layer.shadowOpacity = shadowOpacity
self.layer.shadowOffset = CGSize(width: 0, height: 0)
self.layer.shadowRadius = 6
self.layer.cornerRadius = radius
// self.layer.masksToBounds = true // 不能使用 不然阴影会被裁剪
}