是否可以在不使用UIBezierPath

时间:2017-09-01 10:17:57

标签: ios swift core-graphics

我知道使用UIBezierPath()绘制一条虚线,如:

let path = UIBezierPath()
path.setLineDash([CGFloat(4), CGFloat(4)], count: 2, phase: 0)
path.lineCapStyle = CGLineCap.round
path.move(to: startPoint)
path.addLine(to: endPoint)
path.stroke()

工作正常。但是我怎么能在上下文中绘制虚线?如下所示代码可以绘制实线,无论我添加

context.setLineDash(phase: 3, lengths: [3,2])

整个代码:

override func draw(_ rect: CGRect) {
        if let context = UIGraphicsGetCurrentContext() {
            let startPoint = CGPoint(x: 50, y: 10)
            let endPoint = CGPoint(x: rect.width-100, y: 10)
            context.setLineDash(phase: 3, lengths: [3,2])
            context.setLineWidth(10)
            context.move(to: startPoint)
            context.addLine(to: endPoint)
            context.setStrokeColor(UIColor.red.cgColor)
            context.setLineCap(.round)
            context.strokePath()

        }
    }

结果是:

enter image description here

有什么不对吗?

1 个答案:

答案 0 :(得分:1)

考虑一下......

线宽为10。 线帽是圆的。 所以线帽的半径是5。

<强> N.B。线条终止于线帽的中心点(不在帽子的末端)。

每个短划线的长度为3,线间距为2。

因此,帽子的半径远大于线条之间的间隙。所以每一行都与下一行重叠。

尝试将线长设为......

[3, 12]

这应该使得线条3点长,帽子半径为5,然后帽子两端之间的间隙为2(12 - 5 - 5)。