视图末端的 CAShapeLayer 虚线剪裁

CAShapeLayer dashed line clipping at end of view

好的,所以我正在尝试在视图内绘制一条虚线,这应该相当简单,但无论我尝试了什么,我都会在两端剪裁破折号,我想要破折号没有任何剪裁段。这是我做的扩展(紫色背景颜色就在那里,所以我可以看到框架)

extension UIView {
public func addDashedLineToView(_ color : UIColor) {
    self.backgroundColor = UIColor.purple
    let cgColor = color.cgColor

    let shapeLayer: CAShapeLayer = CAShapeLayer()
    let frameSize = self.frame.size
    let shapeRect = CGRect(x: 0, y: 0, width: frameSize.width, height: frameSize.height)

    shapeLayer.bounds = shapeRect
    shapeLayer.position = CGPoint(x: frameSize.width / 2, y: frameSize.height)
    shapeLayer.fillColor = UIColor.clear.cgColor
    shapeLayer.strokeColor = cgColor
    shapeLayer.lineWidth = 6
    shapeLayer.lineCap = kCALineCapRound
    shapeLayer.lineJoin = kCALineJoinRound
    shapeLayer.lineDashPattern = [8, 10]

    let path: CGMutablePath = CGMutablePath()
    path.move(to: .zero)
    path.addLine(to: CGPoint(x: self.frame.width, y: 0))
    shapeLayer.path = path

    self.layer.addSublayer(shapeLayer)
    self.layer.masksToBounds = true
}

这是最终效果的屏幕截图。

不确定我在哪里搞砸了,但我知道我一定做错了什么,因为在 swift 中画一条虚线不应该这么难(我希望如此)。

您可以通过lineDashPhase调整图案的起始位置。尝试

shapeLayer.lineDashPhase = -4