如果您有 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)