【问题标题】:Divide a line in n equal parts将一条线分成n等份
【发布时间】:2017-12-12 18:54:47
【问题描述】:

我正在从 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)
                }
            }
        }

【问题讨论】:

  • 抱歉,这个问题不清楚。请edit你的问题说清楚。包括一个你想要做什么的具体例子。
  • 将 x 和 y 间隔分成 n 个相等的部分,并从 x/y 对创建点。
  • 其实这是我想做但不知道怎么做的
  • @rmaddy 请检查我的编辑

标签: swift uiview geometry draw


【解决方案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)]

【讨论】:

  • 嗨马丁,谢谢你的回答,请检查我的编辑,它是轻微的偏移。我用过你的代码。
  • @pankaj:对不起,我不明白为什么它不适合你。正如您在我的示例中所看到的,数组中的第一个点是给定的初始点,数组中的最后一个点是给定的端点,并且所有点的距离都相同。
  • 你的代码很完美。在做了一些研究后,我发现它在我的绘图代码中有点偏移。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-06
  • 2020-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-02
相关资源
最近更新 更多