I have a line segment defined by two pointF
s, along with a 2D bounding rectangle. I want to extend the line segment as much as possible in both directions so t
Improved andredor's code - Added edge cases for when line intersects top and bottom or left and right edges. The provided code is for Processing to test the algorithm. The first point is set by clicking the mouse and the second point continuously updates with the current mouse pointer position.
int px = 100, py = 100;
void setup() {
size(480, 640);
background(102);
}
void draw() {
stroke(255);
rect(0, 0, 480, 640);
stroke(100);
if (mousePressed == true) {
px = mouseX;
py = mouseY;
}
extendLine(0, 0, 480, 640, px, py, mouseX, mouseY);
}
void extendLine(int xmin, int ymin, int xmax, int ymax, int x1, int y1, int x2, int y2) {
if (y1 == y2) {
line(xmin, y1, xmax, y1);
return;
}
if(x1 == x2) {
line(x1, ymin, x1, ymax);
return;
}
int y_for_xmin = y1 + (y2 - y1) * (xmin - x1) / (x2 - x1);
int y_for_xmax = y1 + (y2 - y1) * (xmax - x1) / (x2 - x1);
int x_for_ymin = x1 + (x2 - x1) * (ymin - y1) / (y2 - y1);
int x_for_ymax = x1 + (x2 - x1) * (ymax - y1) / (y2 - y1);
if (ymin <= y_for_xmin && y_for_xmin <= ymax
&& ymin <= y_for_xmax && y_for_xmax <= ymax) {
line(xmin, y_for_xmin, xmax, y_for_xmax);
return;
} else if (ymin <= y_for_xmin && y_for_xmin <= ymax) {
if (xmin <= x_for_ymax && x_for_ymax <= xmax) {
line(xmin, y_for_xmin, x_for_ymax, ymax);
return;
}
else if(xmin <= x_for_ymin && x_for_ymin <= xmax) {
line(xmin, y_for_xmin, x_for_ymin, ymin);
return;
}
} else if (ymin <= y_for_xmax && y_for_xmax <= ymax){
if (xmin <= x_for_ymin && x_for_ymin <= xmax){
line(x_for_ymin, ymin, xmax, y_for_xmax);
return;
}
if(xmin <= x_for_ymax && x_for_ymax <= xmax){
line(x_for_ymax, ymax, xmax, y_for_xmax);
return;
}
} else if (xmin <= x_for_ymin && x_for_ymin <= xmax
&& xmin <= x_for_ymax && x_for_ymax <= xmax) {
line(x_for_ymin, ymin, x_for_ymax, ymax);
return;
}
}