3

I have a CAShapeLayer with bottom rounded corners only. What I want is to add a shadow at the bottom, but it's not working, even though the code looks obviously right. All it does it round the bottom corners but I don't see a shadow.

let shapeLayer = CAShapeLayer()

    let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: [.bottomLeft, .bottomRight], cornerRadii: CGSize(width: 20, height: 20)).cgPath
    shapeLayer.path = path

    shapeLayer.shadowColor = UIColor(r: 233, g: 233, b: 233).cgColor
    shapeLayer.shadowOffset = CGSize(width: 0.0, height: 2.8)
    shapeLayer.shadowOpacity = 1.0
    shapeLayer.shadowRadius = 0.0
    shapeLayer.shouldRasterize = true
    shapeLayer.rasterizationScale = UIScreen.main.scale

    layer.rasterizationScale = UIScreen.main.scale
    layer.mask = shapeLayer
rocky raccoon
  • 514
  • 1
  • 8
  • 23

2 Answers2

2

The shapeLayer is rounding the corners of your view because it's set as the layer's mask. You probably want to add it as a sublayer instead.

Old:

layer.mask = shapeLayer

New:

layer.addSublayer(shapeLayer)

I wrote another answer about adding a shadow to a view with rounded corners here if it helps: https://stackoverflow.com/a/41475658/6658553

Community
  • 1
  • 1
nathangitter
  • 9,607
  • 3
  • 33
  • 42
  • 1
    thanks! I got an idea from this question. All I did was create a dummy background view with a drop shadow; and insert it into the view (using `insertSubView`) that had the rounded corners. – rocky raccoon May 04 '17 at 19:34
  • 6
    adding the sublayer to my layer makes the view entirely black – Fred Novack Jun 13 '17 at 17:34
2

Another solution,

The following UIView extension will work with any shape you mask the view with

extension UIView {

  func addShadow() {
     self.backgroundColor = UIColor.clear
     let roundedShapeLayer = CAShapeLayer()
     let roundedMaskPath = UIBezierPath(roundedRect: self.bounds,
                                       byRoundingCorners: [.topLeft, .bottomLeft, .bottomRight],
                                       cornerRadii: CGSize(width: 8, height: 8))

     roundedShapeLayer.frame = self.bounds
     roundedShapeLayer.fillColor = UIColor.white.cgColor
     roundedShapeLayer.path = roundedMaskPath.cgPath

     self.layer.insertSublayer(roundedShapeLayer, at: 0)

     self.layer.shadowOpacity = 0.4
     self.layer.shadowOffset = CGSize(width: -0.1, height: 4)
     self.layer.shadowRadius = 3
     self.layer.shadowColor = UIColor.lightGray.cgColor
   }
}
Aviran
  • 5,160
  • 7
  • 44
  • 76