当我有线的起点和终点时,在对角线上找到一个点

时间:2011-02-14 11:52:16

标签: vb.net

您正在寻求帮助

我的论坛上的图片框上画了一条对角线,我需要知道用户是否点击了该行

我有线的起点和终点以及鼠标x,y位置

所以我基本上需要找出鼠标的x,y是否在线上。

任何人都可以帮忙吗?

由于

2 个答案:

答案 0 :(得分:3)

示例:线起点(A)为(0,0),END点(B)为(10,5)。 因此,线的斜率是:

m(slope) = (y2 - y1) / (x2 - x1) 
         = (5 - 0) / (10 - 0)
         = 5 / 10
         = 0.5

要检查您的点(x,y)(C)是否在线上,它必须具有与A-> C和C-> B相同的斜率。所以再次进行相同的计算。说点是(4,2)

m(AC) = (2 - 0) / (4 - 0)
      = 2 / 4
      = 0.5

m(CB) = (5 - 2) / (10 - 4)
      = 3 / 6
      = 0.5

因此,这一点将在AB线上。

如果点是(20,10)

m(AC) = (10 - 0) / (20 - 0)
      = 10 / 20
      = 0.5

然而:

m(CB) = (5 - 10) / (10 - 20)
      = -5 / -10
      = -0.5

同样,如果点是(2,2)

m(AC) = (2 - 0) / (2 - 0)
      = 2 / 2
      = 1

m(CB) = (5 - 2) / (10 - 2)
      = 3 / 8
      = 0.375

所以要点在一行m(AB) == m(AC) == m(CB)

您可能需要进行一些工作,因为您可能无法获得小数值,并且您的线宽可能超过一个像素,但这些基本原则应该可以帮助您完成。

答案 1 :(得分:1)

给定两点,(2,4)和(-1,-2)确定线的斜率截距形式。

1.  Determine the slope

y1-y2   4-(-2)   6
----- = ------= --- = 2 = M
x1-x2   2-(-1)   3


2. To slope intercept form using one of the original points and slope from above.

(y - y1) = m(x - x1)

(y - 4) = 2(x - 2)

y - 4 = 2x - 4

y = 2x + 0 (0 is y intercept)

y = 2x  (y = 2x + 0)  is in slope intercept form


3. To determine if a point lies on the line, plug and chug with the new point.

  new point (1,2) does y = 2x?  2 = 2(1) = true so (1,2) is on the line.
  new point (2,2) does y = 2x?  2 = 2(2) = false so (2,2) is not on the line.

在你原来的问题中你说过,但我认为你可能意味着线段。如果你的意思是后者,你还需要验证新的x和y是否在给定段的范围内。

代码看起来像这样

    Dim pta As Point = New Point(2, 4)
    Dim ptb As Point = New Point(-1, -2)

    Dim M As Double
    If pta.X - ptb.X <> 0 Then
        M = (pta.Y - ptb.Y) / (pta.X - ptb.X)
    End If

    '(y - pta.y) = M(x - pta.x)
    'y - pta.y = Mx - m(pta.x)
    'y  = Mx - M(pta.x) + pta.y

    Dim yIntercept As Double = (-M * pta.X) + pta.Y

    Dim ptN1 As Point = New Point(1, 2)
    Dim ptN2 As Point = New Point(2, 2)

    If ptN1.Y = (M * (ptN1.X)) + yIntercept Then
        Stop
    Else
        Stop
    End If

    If ptN2.Y = (M * (ptN2.X)) + yIntercept Then
        Stop
    Else
        Stop
    End If