因此,我试图找出一种方法来实现在绘图区域中选择线条或边线的方法,但是我的数学有点缺乏。这是我到目前为止所得到的:
我知道我可以遍历行列表,但是我不知道如何构建一种算法来通过给定坐标(即单击鼠标)选择一条线。任何人有任何想法或向我指出正确的方向吗?
// 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; }
最好的方法是使用直线的相交方法。就像提到的另一个用户一样,您需要在单击的位置周围留一个缓冲区。因此,以鼠标坐标为中心创建一个矩形,然后测试该矩形与线的交点。这是一些应该起作用的代码(没有编译器或任何工具,但应易于修改)
// 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;
}