代码之家  ›  专栏  ›  技术社区  ›  kvv

如何在另外两条平行线之间画一条垂直直线?

  •  -3
  • kvv  · 技术社区  · 8 年前

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

    1 回复  |  直到 8 年前
        1
  •  0
  •   Matic Oblak    8 年前

    如果你有两条平行线,并希望在它们之间画垂直线,你将需要一个额外的点。假设该点位于第一条线的中间(称为 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)