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坝冕,默認(rèn)(0, -3),這個(gè)跟shadowRadius配合使用
subLayer.shadowOpacity = Float(shadowOpacity) //陰影透明度
subLayer.shadowRadius = 5;//陰影半徑足淆,默認(rèn)3
self.superview?.layer.insertSublayer(subLayer, below: self.layer)
}
經(jīng)過測(cè)試添加的CALayer會(huì)偏移一點(diǎn) 不知道是啥問題 需要修正
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功炮,默認(rèn)(0, -3),這個(gè)跟shadowRadius配合使用
subLayer.shadowOpacity = shadowOpacity;//陰影透明度
subLayer.shadowRadius = 3;//陰影半徑,默認(rèn)3
[self.superview.layer insertSublayer:subLayer below:self.layer];
}
修改版
注意:
1.使用此方法 添加圓角與陰影View之上不能出現(xiàn)其他View將其遮蓋(因?yàn)閟elf.layer.masksToBounds = false)不能進(jìn)行多余部分裁剪 故有遮蓋會(huì)將圓角遮蓋
2.self.layer.masksToBounds = true 陰影會(huì)被裁剪掉
image.png
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 // 不能使用 不然陰影會(huì)被裁剪
}