CAShapeLayer can't use rect path?

Viewed 1651

I draw a dash border

let centerView = UIView()
centerView.frame = CGRect(x: 100, y: 100, width: 80, height: 50)
        
let shapeLayer = CAShapeLayer()
shapeLayer.fillColor = nil
shapeLayer.strokeColor = UIColor.gray.cgColor
        
shapeLayer.lineDashPattern = [3, 2]
shapeLayer.lineWidth = 0.5
shapeLayer.path = UIBezierPath(
  roundedRect: centerView.bounds,
  cornerRadius: 22
).cgPath
        
view.addSubview(centerView)
centerView.layer.addSublayer(shapeLayer)

When I tap Debug View Hierarchy

Runtime issue:

A CAShapeLayer is used with a path that's a rect, a rounded-rect, or an ellipse. Instead, use an appropriately transformed plain CALayer with cornerRadius set.

How to fix it?

1 Answers

Use the layer's shadowPath instead of path like this:

shapeLayer.shadowPath = UIBezierPath(
  roundedRect: centerView.bounds,
  cornerRadius: 22
).cgPath
Related