此种方式不会在
UIVisualEffectView
下产生阴影颜色,而是围绕UIVisualEffectView
生成的阴影效果。
/// UIVisualEffectView 设置阴影
open func setup(_ blurEffectView: UIVisualEffectView, rect: CGRect, color: UIColor = .lightGray, offset: CGSize = .zero, opacity: Float = 0.5, radius: CGFloat = 3) {
let shadowLayer = CALayer()
let mutablePath = CGMutablePath()
let maskLayer = CAShapeLayer()
let rect = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: blurEffectView.frame.height)
let shadowPath = UIBezierPath(rect: rect).cgPath
let shadowFrame = rect.insetBy(dx: -2 * radius, dy: -2 * radius).offsetBy(dx: offset.width, dy: offset.height)
let shadowRect = CGRect(origin: .zero, size: shadowFrame.size)
let shadowTransform = CGAffineTransform(translationX: -rect.origin.x - offset.width + 2 * radius, y: -rect.origin.y - offset.height + 2 * radius)
shadowLayer.shadowPath = shadowPath
shadowLayer.shadowOffset = offset
shadowLayer.shadowOpacity = opacity
shadowLayer.shadowRadius = radius
shadowLayer.shadowColor = color.cgColor
mutablePath.addRect(shadowRect)
mutablePath.addPath(shadowLayer.shadowPath!, transform: shadowTransform)
mutablePath.closeSubpath()
maskLayer.frame = shadowFrame
maskLayer.fillRule = kCAFillRuleEvenOdd
maskLayer.path = mutablePath
shadowLayer.mask = maskLayer
blurEffectView.layer.superlayer?.insertSublayer(shadowLayer, above: blurEffectView.layer)
}