如何对齐 UIBezierPath 圆破折号

How to align UIBezierPath circle dashes

我正在尝试使用 UIBezierPath 绘制一个罗盘,并在线条中添加破折号以标记东、南、北方向和它们之间的点。破折号似乎偏移了(它们没有对齐),尤其是在北向和南向,而我这样做的方式似乎在路径关闭时添加了额外的破折号。

let windCircleOrigin = CGPoint(x: self.center.x * 1.3, y: self.bounds.height / 2.0 - 10)
let windCircleRadius = CGFloat(self.bounds.height * 0.3)
let windCirclePath: UIBezierPath = UIBezierPath(arcCenter: windCircleOrigin, radius: windCircleRadius,startAngle: 0,  endAngle: CGFloat(M_PI) * 2.0, clockwise: true)
        windCirclePath.lineWidth = 6
let dashes: [CGFloat] = [windCirclePath.lineWidth * 0, windCirclePath.lineWidth * 3 ]
        windCirclePath.setLineDash(dashes, count: dashes.count
            , phase: 0.0)
UIColor.whiteColor().setFill()
UIColor.whiteColor().setStroke()
windCirclePath.stroke()
textView(self.windSpeedLabel! + " mph", x: windCircleOrigin.x - 20.0, y: windCircleOrigin.y - 8.0, color: UIColor.whiteColor(), width: 50.0, height: 20.0)
textView("N", x: windCircleOrigin.x - 7.0, y: windCircleOrigin.y - 70.0, color: UIColor.whiteColor(), width: 20, height: 20)
textView("S", x: windCircleOrigin.x - 7.0, y: windCircleOrigin.y + 50.0, color: UIColor.whiteColor(), width: 20, height: 20)
textView("W", x: windCircleOrigin.x - 70.0, y: windCircleOrigin.y - 8.0, color: UIColor.whiteColor(), width: 20, height: 20)
textView("E", x: windCircleOrigin.x + 60.0, y: windCircleOrigin.y - 8.0, color: UIColor.whiteColor(), width: 20, height: 20)

func textView(text: String, x: CGFloat, y: CGFloat, color: UIColor, width: CGFloat, height: CGFloat) {
    let textView = UILabel(frame: CGRectMake(x, y, width, height))
    textView.textAlignment = NSTextAlignment.Left
    textView.textColor = color
    textView.backgroundColor = UIColor.clearColor()
    textView.font = UIFont(name: "HelveticaNeue-Light", size: 12.0)
    textView.text = text
    self.addSubview(textView)
}

相反,我建议单独绘制每个刻度。然后你就可以轻松控制他们的位置了。

像这样:

let path = UIBezierPath()
let innerRadius: CGFloat = 50
let outerRadius: CGFloat = 60
let numTicks = 24

for i in 0..<numTicks {
    let angle = CGFloat(i) * CGFloat(2*M_PI) / CGFloat(numTicks)
    let inner = CGPoint(x: innerRadius * cos(angle), y: innerRadius * sin(angle))
    let outer = CGPoint(x: outerRadius * cos(angle), y: outerRadius * sin(angle))
    path.moveToPoint(inner)
    path.addLineToPoint(outer)
}

然后你可以用你想要的任何 lineWidth(和 lineCapStyle)描边这条路径。

使用 CGPath 非常简单。不确定是否可以使用 UIBezierPath 完成相同的操作。

Swift 5.0

path.copy(dashingWithPhase: 0, lengths: [(.pi * radius) / dashCount])