如何选择一条线 [英] How to select a line
问题描述
所以我试图弄清楚如何实现一种在绘图区域中选择线条或边缘的方法,但我的数学有点欠缺.这是我目前得到的:
So I'm trying to figure out how to implement a method of selecting lines or edges in a drawing area but my math is a bit lacking. This is what I got so far:
- 线的集合,每条线有两个终点(一个开始,一个结束线)
- 线条在画布上正确绘制
- 单击画布时会收到鼠标单击事件,因此我可以获取鼠标指针的 x 和 y 坐标
我知道我可以遍历行列表,但我不知道如何构建一个算法来通过给定的坐标(即鼠标单击)选择一条线.有人有任何想法或为我指明正确的方向吗?
I know I can iterate through the list of lines, but I have no idea how to construct an algorithm to select a line by a given coordinate (i.e. the mouse click). Anyone got any ideas or point me to the right direction?
// 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 方法.就像另一个用户提到的那样,您需要在他们单击的位置周围有一个缓冲区.因此,创建一个以鼠标坐标为中心的矩形,然后测试该矩形是否与您的线相交.这是一些应该可以工作的代码(没有编译器或任何东西,但应该很容易修改)
Best way to do this is to use the intersects method of the line. Like another user mentioned, you need to have a buffer area around where they clicked. So create a rectangle centered around your mouse coordinate, then test that rectangle for intersection with your line. Here's some code that should work (don't have a compiler or anything, but should be easily modifiable)
// 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;
}
这篇关于如何选择一条线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!