Rect.cpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. #include "Rect.h"
  2. #include <AK/StdLibExtras.h>
  3. void Rect::intersect(const Rect& other)
  4. {
  5. int l = max(left(), other.left());
  6. int r = min(right(), other.right());
  7. int t = max(top(), other.top());
  8. int b = min(bottom(), other.bottom());
  9. if (l > r || t > b) {
  10. m_location = {};
  11. m_size = {};
  12. return;
  13. }
  14. m_location.set_x(l);
  15. m_location.set_y(t);
  16. m_size.set_width((r - l) + 1);
  17. m_size.set_height((b - t) + 1);
  18. }
  19. Rect Rect::united(const Rect& other) const
  20. {
  21. if (is_null())
  22. return other;
  23. if (other.is_null())
  24. return *this;
  25. Rect rect;
  26. rect.set_left(min(left(), other.left()));
  27. rect.set_top(min(top(), other.top()));
  28. rect.set_right(max(right(), other.right()));
  29. rect.set_bottom(max(bottom(), other.bottom()));
  30. return rect;
  31. }
  32. Vector<Rect, 4> Rect::shatter(const Rect& hammer) const
  33. {
  34. Vector<Rect, 4> pieces;
  35. if (!intersects(hammer)) {
  36. pieces.unchecked_append(*this);
  37. return pieces;
  38. }
  39. Rect top_shard {
  40. x(),
  41. y(),
  42. width(),
  43. hammer.y() - y()
  44. };
  45. Rect bottom_shard {
  46. x(),
  47. hammer.y() + hammer.height(),
  48. width(),
  49. (y() + height()) - (hammer.y() + hammer.height())
  50. };
  51. Rect left_shard {
  52. x(),
  53. max(hammer.y(), y()),
  54. hammer.x() - x(),
  55. min((hammer.y() + hammer.height()), (y() + height())) - max(hammer.y(), y())
  56. };
  57. Rect right_shard {
  58. hammer.x() + hammer.width(),
  59. max(hammer.y(), y()),
  60. right() - hammer.right(),
  61. min((hammer.y() + hammer.height()), (y() + height())) - max(hammer.y(), y())
  62. };
  63. if (intersects(top_shard))
  64. pieces.unchecked_append(top_shard);
  65. if (intersects(bottom_shard))
  66. pieces.unchecked_append(bottom_shard);
  67. if (intersects(left_shard))
  68. pieces.unchecked_append(left_shard);
  69. if (intersects(right_shard))
  70. pieces.unchecked_append(right_shard);
  71. return pieces;
  72. }
  73. void Rect::align_within(const Rect& other, TextAlignment alignment)
  74. {
  75. switch (alignment) {
  76. case TextAlignment::Center:
  77. center_within(other);
  78. return;
  79. case TextAlignment::TopLeft:
  80. set_location(other.location());
  81. return;
  82. case TextAlignment::TopRight:
  83. set_x(other.x() + other.width() - width());
  84. set_y(other.y());
  85. return;
  86. case TextAlignment::CenterLeft:
  87. set_x(other.x());
  88. center_vertically_within(other);
  89. return;
  90. case TextAlignment::CenterRight:
  91. set_x(other.x() + other.width() - width());
  92. center_vertically_within(other);
  93. return;
  94. }
  95. }