代码片段:
extension UIView {
func dropShadow(scale: Bool = true) {
layer.masksToBounds = false
layer.shadowColor = UIColor.black.cgColor
layer.shadowOpacity = 0.5
layer.shadowOffset = CGSize(width: -1, height: 1)
layer.shadowRadius = 1
layer.shadowPath = UIBezierPath(rect: bounds).cgPath
layer.shouldRasterize = true
layer.rasterizationScale = scale ? UIScreen.main.scale : 1
}
func dropShadow(color: UIColor, opacity: Float = 0.5, offSet: CGSize, radius: CGFloat = 1, scale: Bool = true) {
layer.masksToBounds = false
layer.shadowColor = color.cgColor
layer.shadowOpacity = opacity
layer.shadowOffset = offSet
layer.shadowRadius = radius
layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath
layer.shouldRasterize = true
layer.rasterizationScale = scale ? UIScreen.main.scale : 1
}
}
注意:如果您没有将任何参数传递给该函数,则scale参数默认为true。您可以为函数中的任何参数定义默认值,方法是在该参数的类型之后为该参数分配一个值。如果定义了默认值,则可以在调用函数时忽略该参数。
输出1:
shadowView.dropShadow()
输出2:
shadowView.dropShadow(color: .red, opacity: 1, offSet: CGSize(width: -1, height: 1), radius: 3, scale: true)
layer.shouldRasterize = true
将使阴影静止,并为的初始状态造成阴影UIView
。因此,我建议不要layer.shouldRasterize = true
在动态布局中使用,例如view UITableViewCell
。