将一条线分成 n 等份

Divide a line in n equal parts

我正在从点 A(x1,y1) 到点 B(x2,y2) 画一条线。现在我需要把这条线分成 n 等份。线不是直的,所以我无法根据 x 轴和宽度计算点。 我画线如下:

let lineTop = DrawFiguresViewModel.getLine(fromPoint: CGPoint(x: point.x, y: point.y), toPoint: CGPoint(x: (point.x-100), y: (point.y-100)))
self.view.layer.addSublayer(lineTop)

class DrawFiguresViewModel{
    class func getLine(fromPoint start: CGPoint, toPoint end:CGPoint) -> CALayer{
        let line = CAShapeLayer()
        let linePath = UIBezierPath()
        linePath.move(to: start)
        linePath.addLine(to: end)
        line.path = linePath.cgPath
        line.strokeColor = Colors.lineColor.cgColor
        line.lineWidth = 2
        line.lineJoin = kCALineJoinRound
        return line
    }
}

在这个方向上的任何领先都会很棒。

编辑1: 我想画像 这样的图表。

我可以画粗线,但现在我需要用文本原因和原因画细线。在垂直(倾斜)线上等距可能有多个原因。

编辑2: 添加 Martin 的代码后,我得到它
虽好但略有抵消。同样因为它是 n+1 我在绘制之前删除了 0 索引值。

编辑3: 以下是使用 Martin 函数绘制线条的代码:

if(node.childs.count > 0){
            var arrPoints = divideSegment(start: CGPoint(x: point.x, y: point.y), end: CGPoint(x: (point.x-100), y: (point.y-100)), parts: node.childs.count)
            arrPoints.remove(at: 0)
            print(arrPoints)
            for (index,obj) in node.childs.enumerated(){
                if let nodeN = obj as? DataNode{
                    let pointN = arrPoints[index]
                    drawLevel1Line(point: pointN, nodeTitle: nodeN.title)
                }
            }
        }

您从初始点开始,然后将 x 坐标和 y 坐标重复递增固定量,该固定量计算如下 n 步到达段的终点(换句话说:线性插值):

/// Returns an array of (`n` + 1) equidistant points from `start` to `end`.
func divideSegment(from start: CGPoint, to end: CGPoint, parts n: Int) -> [CGPoint] {
    let ΔX = (end.x - start.x) / CGFloat(n)
    let ΔY = (end.y - start.y) / CGFloat(n)
    return (0...n).map {
        CGPoint(x: start.x + ΔX * CGFloat([=10=]),
                y: start.y + ΔY * CGFloat([=10=])) 
    }
}

示例:

print(divideSegment(from: CGPoint(x: 1, y: 1), to: CGPoint(x: 4, y: 5), parts: 4))
// [(1.0, 1.0), (1.75, 2.0), (2.5, 3.0), (3.25, 4.0), (4.0, 5.0)]