3

what I'm trying to achieve is to apply a mask to UIView together with shadow, border and cornerRadius.

By now I'm able to set mask, cornerRadius and border. Issue is with trying to set shadow.

This is my code so far

let path = UIBezierPath(roundedRect: rect, byRoundingCorners: UIRectCorner.allCorners, cornerRadii: CGSize(width: radius, height: radius))

let mask = CAShapeLayer()
mask.path = path.cgPath
layer.mask = mask

let frameLayer = CAShapeLayer()
frameLayer.path = path.cgPath
frameLayer.lineWidth = width
frameLayer.strokeColor = color.cgColor
frameLayer.fillColor = nil

layer.addSublayer(frameLayer)

Issue is if I try to set shadow to frameLayer or layer, I'm not getting desired results. It gets clipped by mask. Is there any way to achieve this except to use next lines of code?

layer.cornerRadius = 5
layer.borderColor = color.cgColor
layer.borderWidth = width
layer.shadowColor = shadowColor.cgColor
layer.shadowOpacity = opacity
layer.shadowRadius = radius
layer.shadowOffset = offset
clipsToBounds = true

Both snippets are intended to be used inside UIView subclass, so if anyone can help me regarding this I would really appreciate it. Thanks

If there is something else needed or something unclear please let me know

Kuldeep
  • 4,466
  • 8
  • 32
  • 59
Baki
  • 490
  • 4
  • 19

1 Answers1

1

Heh, just half hour later I managed to find solution to my own problem:

let path = UIBezierPath(roundedRect: rect, byRoundingCorners: UIRectCorner.allCorners, cornerRadii: CGSize(width: radius, height: radius))

let frameLayer = CAShapeLayer()
frameLayer.path = path.cgPath
frameLayer.shadowPath = path.cgPath

frameLayer.lineWidth = borderWidth
frameLayer.strokeColor = borderColor.cgColor
frameLayer.fillColor = backgroundColor?.cgColor
frameLayer.shadowOffset = shadowOffset
frameLayer.shadowOpacity = shadowOpacity
frameLayer.shadowRadius = shadowRadius
frameLayer.shadowColor = shadowColor.cgColor

layer.mask = frameLayer
layer.insertSublayer(frameLayer, at: 0)
Baki
  • 490
  • 4
  • 19