Extending a line segment to fit into a bounding box

前端 未结 5 1643
误落风尘
误落风尘 2021-01-12 03:25

I have a line segment defined by two pointFs, along with a 2D bounding rectangle. I want to extend the line segment as much as possible in both directions so t

5条回答
  •  北海茫月
    2021-01-12 04:09

    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;
        }
    }
    

提交回复
热议问题