Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
100 views
in Technique[技术] by (71.8m points)

java - 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:

  • A collection of lines, each line has two end points (one to start and one to end the line)
  • The lines are drawn correctly on a canvas
  • Mouse clicks events are received when clicking the canvas, so I can get the x and y coordinate of the mouse pointer

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;

}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...