如何选择一条线

Spo*_*ike 2 java algorithm graphics 2d

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

  • 一组线,每一行有两个端点(一个开始,一个开始结束)
  • 线条在画布上正确绘制
  • 单击画布时会收到鼠标单击事件,因此我可以获取鼠标指针的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;
}
Run Code Online (Sandbox Code Playgroud)

I82*_*uch 7

最好的方法是使用该行的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;
Run Code Online (Sandbox Code Playgroud)

}

  • 或者只是看看ptLineDist()是否小于某个阈值.对于较大的"缓冲区大小",您将获得较少的奇怪结果. (2认同)

Toj*_*oji 5

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

线数学在这里:

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

点到线段的最短距离