设置UIView的圆角+阴影

网上很多这个感觉好麻烦啊,下面直接贴代码吧

extension CALayer {
    
    /// 设置圆角+阴影
    /// - Parameters:
    ///   - blur: 模糊值
    ///   - color: 阴影颜色
    ///   - alpha: 透明度
    ///   - radius: 圆角
    ///   - x: 宽
    ///   - y: 高
    ///   - spread: 阴影的 “扩展”
    func setShadowLayer(blur: CGFloat,
                        color: UIColor,
                        alpha: CGFloat, radius: CGFloat,
                        x: CGFloat, y: CGFloat,
                        spread: CGFloat) {
        
        shadowRadius = blur
        shadowColor = color.cgColor
        shadowOpacity = Float(alpha)
        cornerRadius = radius
        shadowOffset = CGSize.init(width: x, height: y)
        
        let rect = bounds.insetBy(dx: -spread, dy: -spread)
        let path = UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius)
        shadowPath = path.cgPath
    }
}

调用

let view = UIView.init(frame: CGRect.init(x: 150, y: 200, width: 100, height: 100))
view.backgroundColor = .systemOrange
self.view.addSubview(view)
view.layer.setShadowLayer(blur: 5, color: .black, alpha: 0.5, radius: 5, x: 0, y: 3, spread: 0)

效果


image.png

你可能感兴趣的:(设置UIView的圆角+阴影)