如何选择一条线

所以我试图找出如何实现在绘图区域中选择线条或边缘的方法,但我的数学有点缺乏。 这是我到目前为止所得到的:

  • 一组线,每一行有两个端点(一个开始,一个开始结束)
  • 在canvas上正确绘制线条
  • 单击canvas时会收到鼠标单击事件,因此我可以获取鼠标指针的x和y坐标

我知道我可以遍历行列表,但我不知道如何构造算法来通过给定坐标(即鼠标单击)选择行。 有人有任何想法或指出我正确的方向?

// import java.awt.Point public Line selectLine(Point mousePoint) { for (Line l : getLines()) { Point start = l.getStart(); Point end = l.getEnd(); if (canSelect(start, end, mousePoint)) { return l; // found line! } } return null; // could not find line at mousePoint } public boolean canSelect(Point start, Point end, Point selectAt) { // How do I do this? return false; } 

最好的方法是使用该行的intersects方法。 与其他提到的用户一样,您需要在他们点击的位置周围放置一个缓冲区。 因此,创建一个以鼠标坐标为中心的矩形,然后测试该矩形是否与您的线相交。 这里有一些应该工作的代码(没有编译器或任何东西,但应该很容易修改)

 // Width and height of rectangular region around mouse // pointer to use for hit detection on lines private static final int HIT_BOX_SIZE = 2; public void mousePressed(MouseEvent e) { int x = e.getX(); int y = e.getY(); Line2D clickedLine = getClickedLine(x, y); } /** * Returns the first line in the collection of lines that * is close enough to where the user clicked, or null if * no such line exists * */ public Line2D getClickedLine(int x, int y) { int boxX = x - HIT_BOX_SIZE / 2; int boxY = y - HIT_BOX_SIZE / 2; int width = HIT_BOX_SIZE; int height = HIT_BOX_SIZE; for (Line2D line : getLines()) { if (line.intersects(boxX, boxY, width, height) { return line; } } return null; 

}

如果您使用2D api,那么这已经得到了解决。

您可以使用Line2D.Double类来表示行。 Line2D.Double类有一个contains()方法,它告诉你Point是否在线上。

好吧,首先,由于数学线没有宽度,因此用户很难完全点击该线。 因此,最好的办法是提出一些合理的缓冲区(如1或2像素,或者如果您的线条以图形方式使用宽度),并计算从鼠标点击到线条的距离。 如果距离落在缓冲区内,则选择该线。 如果您在多个行的缓冲区内,请选择最接近的行。

这里的线数学:

http://mathworld.wolfram.com/Point-LineDistance2-Dimensional.html

点和线段之间的最短距离

对不起,仍然需要数学……这是来自java.awt.geom.Line2D:

public boolean contains(double x,double y)

测试指定的坐标是否在此Line2D的边界内。 实现Shape接口需要此方法,但在Line2D对象的情况下,它总是返回false,因为一行不包含任何区域。

指定者:包含在接口Shape中

参数:x – 要测试的指定点的X坐标y – 要测试的指定点的Y坐标

返回:false,因为Line2D不包含区域。

自:1.2

我推荐Tojis回答