【问题标题】:How to draw a straight perpendicular line between 2 other parallel lines?如何在另外两条平行线之间画一条垂直线?
【发布时间】:2025-12-01 18:45:02
【问题描述】:

enter image description here 我需要使用手指的位置绘制第一条线。 稍后我需要使用手指的位置绘制第二条平行线。 我已经做到了。 主要任务是在这些平行线之间绘制第三条垂直线。 怎么画第三条线?

【问题讨论】:

  • 除了发表一些声明还有什么问题?
  • 这是关于(Swift)编程还是几何/数学的问题?
  • @ElTomato 如何在平行线之间画一条垂直线?
  • @MartinR 关于 Swift 编程

标签: ios swift xcode core-graphics


【解决方案1】:

如果您有 2 条平行线并希望在它们之间绘制垂直线,您将需要 1 个额外点。假设该点位于第一行的中间(称为C)。

还假设我们有以下内容:

L1 // Represents the first line
L2 // Represents the second line
L1.start // Represents the line start point CGPoint
L1.end // Represents the line end point CGPoint

现在你想画一条垂直线到第一条线L1,你需要得到它的normal,这在2D中很简单。首先通过减去给定线direction = CGPoint(x: L1.end.x-L1.start.x, y: L1.end.y-L1.start.y)的起点和终点来获得线方向。现在要获得法线,我们只需反转坐标并将它们除以方向长度:

let length = sqrt(direction.x*direction.x + direction.y*direction.y)
let normal = CGPoint(x: -direction.y/length, y: direction.x/length) // Yes, normal is (-D.y, D.x)

所以说起点是C,现在我们只需要在另一条线上找到终点C + normal*distanceBetweenLines。所以我们需要两条线之间的距离,最好通过点积接收...

首先,我们需要在两条线的任意一对点之间有一个向量(一个点在第一行,另一个在第二行)。所以让我们采取

let between = CGPoint(x: L1.start.x-L2.start.x, y: L1.start.y-L2.start.y)

现在我们需要用点积将这条线投影到法线,得到投影的长度,即两条线之间的长度

let distanceBetweenLines = between.x*normal.x + between.y*normal.y.

所以现在我们有了所有的点来在两条给定的线之间绘制垂直线,假设这些线是平行的:

L3.start = C
L3.end = CGPoint(x: C.x + normal.x*distanceBetweenLines, y: C.y + normal.y*distanceBetweenLines)

【讨论】:

    最近更新 更多