gpt4 book ai didi

swift - 将一条线分成 n 等份

转载 作者:行者123 更新时间:2023-11-28 06:07:38 25 4
gpt4 key购买 nike

我正在从点 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:我想画像 this 这样的图表.

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

编辑2:添加 Martin 的代码后,我得到的是 this
虽好但略有抵消。同样,因为它是 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($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)]

关于swift - 将一条线分成 n 等份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47779670/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com