How to control shadow spread and blur?

前端 未结 8 1221
终归单人心
终归单人心 2020-12-07 06:51

I have designed UI elements in sketch, and one of them has a shadow with blur 1 and spread 0. I looked at the doc for the views layer property and layer doesnt have anything

8条回答
  •  被撕碎了的回忆
    2020-12-07 07:25

    I really like the answer posted here and suggestions in the comments. This is how I modified that solution:

    extension UIView {
      func applyShadow(color: UIColor, alpha: Float, x: CGFloat, y: CGFloat, blur: CGFloat, spread: CGFloat) {
        layer.masksToBounds = false
        layer.shadowColor = color.cgColor
        layer.shadowOpacity = alpha
        layer.shadowOffset = CGSize(width: x, height: y)
        layer.shadowRadius = blur / UIScreen.main.scale
        if spread == 0 {
          layer.shadowPath = nil
        } else {
          let dx = -spread
          let rect = bounds.insetBy(dx: dx, dy: dx)
          layer.shadowPath = UIBezierPath(rect: rect).cgPath
        }
      }
    }
    

    USAGE:

    myButton.applyShadow(color: .black, alpha: 0.2, x: 0, y: 1, blur: 2, spread: 0)
    

提交回复
热议问题