line.dart 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import 'package:fis_measure/interfaces/date_types/point.dart';
  2. class LineUtils {
  3. // 计算两条直线是否有交点
  4. static DPoint? calculateIntersection(
  5. DPoint startA,
  6. DPoint endA,
  7. DPoint startB,
  8. DPoint endB,
  9. ) {
  10. final lineA = _IntersectionTempLine.fromPoints(startA, endA);
  11. final lineB = _IntersectionTempLine.fromPoints(startB, endB);
  12. if (lineA.isVertical && lineB.isVertical) {
  13. // 两条直线都是垂直线,没有交点
  14. return null;
  15. } else if (lineA.isVertical) {
  16. // 第一条直线是垂直线,交点的x坐标是第一条直线的x坐标
  17. return DPoint(
  18. lineA.intercept, lineB.slope * lineA.intercept + lineB.intercept);
  19. } else if (lineB.isVertical) {
  20. // 第二条直线是垂直线,交点的x坐标是第二条直线的x坐标
  21. return DPoint(
  22. lineB.intercept, lineA.slope * lineB.intercept + lineA.intercept);
  23. } else if (lineA.slope == lineB.slope) {
  24. // 斜率相同,直线平行或重合,没有交点
  25. return null;
  26. } else {
  27. // 斜率不同,计算交点
  28. double x =
  29. (lineB.intercept - lineA.intercept) / (lineA.slope - lineB.slope);
  30. double y = lineA.slope * x + lineA.intercept;
  31. return DPoint(x, y);
  32. }
  33. }
  34. }
  35. class _IntersectionTempLine {
  36. final double slope;
  37. final double intercept;
  38. final bool isVertical;
  39. _IntersectionTempLine(this.slope, this.intercept, this.isVertical);
  40. // 根据两个端点创建直线对象
  41. factory _IntersectionTempLine.fromPoints(DPoint p1, DPoint p2) {
  42. if (p1.x == p2.x) {
  43. // 垂直线
  44. return _IntersectionTempLine(double.nan, p1.x, true);
  45. } else {
  46. // 斜率
  47. double m = (p2.y - p1.y) / (p2.x - p1.x);
  48. // y轴截距
  49. double b = p1.y - m * p1.x;
  50. return _IntersectionTempLine(m, b, false);
  51. }
  52. }
  53. }