extendLinePointsToRectPoints function

(double, double, double, double)? extendLinePointsToRectPoints(
  1. double left,
  2. double top,
  3. double right,
  4. double bottom,
  5. double x1,
  6. double y1,
  7. double x2,
  8. double y2,
)

Extends given line to the given rectangle such that it touches the rectangle points.

Implementation

(double, double, double, double)? extendLinePointsToRectPoints(
  double left,
  double top,
  double right,
  double bottom,
  double x1,
  double y1,
  double x2,
  double y2,
) {
  if (y1 == y2) {
    return (left, y1, right, y1);
  }
  if (x1 == x2) {
    return (x1, top, x1, bottom);
  }

  double yForLeft = y1 + (y2 - y1) * (left - x1) / (x2 - x1);
  double yForRight = y1 + (y2 - y1) * (right - x1) / (x2 - x1);

  double xForTop = x1 + (x2 - x1) * (top - y1) / (y2 - y1);
  double xForBottom = x1 + (x2 - x1) * (bottom - y1) / (y2 - y1);

  if (top <= yForLeft &&
      yForLeft <= bottom &&
      top <= yForRight &&
      yForRight <= bottom) {
    return (left, yForLeft, right, yForRight);
  } else if (top <= yForLeft && yForLeft <= bottom) {
    if (left <= xForBottom && xForBottom <= right) {
      return (left, yForLeft, xForBottom, bottom);
    } else if (left <= xForTop && xForTop <= right) {
      return (left, yForLeft, xForTop, top);
    }
  } else if (top <= yForRight && yForRight <= bottom) {
    if (left <= xForTop && xForTop <= right) {
      return (xForTop, top, right, yForRight);
    }
    if (left <= xForBottom && xForBottom <= right) {
      return (xForBottom, bottom, right, yForRight);
    }
  } else if (left <= xForTop &&
      xForTop <= right &&
      left <= xForBottom &&
      xForBottom <= right) {
    return (xForTop, top, xForBottom, bottom);
  }
  return null;
}