1

How do I draw a horizontal shadow under the bottom of a view?

Currently, I'm drawing it like this

    layer.shadowColor = UIColor.darkGray.cgColor
    layer.shadowOpacity = 0.3
    layer.masksToBounds = false
    layer.shadowRadius = 2
    
    let shadowPath = UIBezierPath()
    shadowPath.move(to: CGPoint(x: 0, y: bounds.height))
    shadowPath.addLine(to: CGPoint(x: bounds.width, y: bounds.height))
    shadowPath.addLine(to: CGPoint(x: bounds.width, y: bounds.height + shadowHeight))
    shadowPath.addLine(to: CGPoint(x: 0, y: bounds.height + shadowHeight))
    shadowPath.close()
    layer.shadowPath = shadowPath.cgPath

But I end up with a small vertical shadow.

Shadow

I'm hoping to just cut off all the vertical shadow like this enter image description here

joels
  • 7,249
  • 11
  • 53
  • 94

1 Answers1

2

It looks like you're using the wrong tool for the job. CALayer's shadow property is meant to simulate the look of a real-world shadow, of course, and for that use it makes sense that the shadow doesn't just stop at the corner, but wraps around it. To get the look that you're describing, draw a gradient instead. Here's some code:

let gradientLayer = CAGradientLayer()
gradientLayer.colors = [UIColor(white: 0.5, alpha: 0.5).cgColor,
                        UIColor(white: 1.0, alpha: 0.0).cgColor]
gradientLayer.frame = layer.bounds
gradientLayer.anchorPoint = layer.anchorPoint
layer.addSublayer(gradientLayer)

And with that I get:

gray gradient

Caleb
  • 124,013
  • 19
  • 183
  • 272
  • Thank you so much. I didn't know that CALayer's shadow property is meant to simulate the look of a real-world shadow – joels Jun 25 '20 at 23:50