划分n等于

时间:2017-12-12 18:54:47

标签: swift uiview geometry draw

我从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
    }
}

任何朝这个方向迈进的人都会很棒。

EDIT1: 我想绘制像this这样的图表。

我能够画出粗线,但现在我需要用文字原因和原因绘制细线。在垂直(倾斜)线上等距离可能有多种原因。

EDIT2: 从Martin添加代码后,我将其作为this发送 虽然它很好,但略有偏移。同样,因为它是n + 1我在绘制它之前删除0索引值。

EDIT3: 以下是使用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)
                }
            }
        }

1 个答案:

答案 0 :(得分:1)

从初始点开始,然后重复递增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($0),
                y: start.y + ΔY * CGFloat($0)) 
    }
}

示例:

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)]