美文网首页
为 UIVisualEffectView 添加阴影效果

为 UIVisualEffectView 添加阴影效果

作者: 冰霜海胆 | 来源:发表于2017-06-05 14:40 被阅读19次

    此种方式不会在 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)
        }
    
    

    相关文章

      网友评论

          本文标题:为 UIVisualEffectView 添加阴影效果

          本文链接:https://www.haomeiwen.com/subject/fnbifxtx.html