diff --git a/SDL2pp/Rect.cc b/SDL2pp/Rect.cc index 8abc42c..55c636a 100644 --- a/SDL2pp/Rect.cc +++ b/SDL2pp/Rect.cc @@ -21,6 +21,8 @@ #include +#include + #include namespace SDL2pp { @@ -129,4 +131,10 @@ void Rect::SetY2(int y2) { rect_.h = y2 - rect_.y + 1; } +bool Rect::Contains(const Point& point) const { + if (IsNull() || point.IsNull()) + return false; + return !(point.GetX() < GetX() || point.GetY() < GetY() || point.GetX() > GetX2() || point.GetY() > GetY2()); +} + } diff --git a/SDL2pp/Rect.hh b/SDL2pp/Rect.hh index e90b3e2..8ac52d9 100644 --- a/SDL2pp/Rect.hh +++ b/SDL2pp/Rect.hh @@ -28,6 +28,8 @@ struct SDL_Rect; namespace SDL2pp { +class Point; + class Rect { private: SDL_Rect rect_; @@ -74,6 +76,8 @@ public: int GetY2() const; void SetY2(int y2); + + bool Contains(const Point& point) const; }; } diff --git a/tests/test_pointrect.cc b/tests/test_pointrect.cc index e7d423f..46653a0 100644 --- a/tests/test_pointrect.cc +++ b/tests/test_pointrect.cc @@ -160,4 +160,17 @@ BEGIN_TEST() EXPECT_TRUE(r.GetX() == 98 && r.GetY() == 97); EXPECT_TRUE(r.GetX2() == 102 && r.GetY2() == 103); } + + { + // Rect contains point + Rect r(10, 20, 5, 5); + + EXPECT_TRUE(r.Contains(Point(10, 20))); + EXPECT_TRUE(r.Contains(Point(14, 24))); + + EXPECT_TRUE(!r.Contains(Point(9, 20))); + EXPECT_TRUE(!r.Contains(Point(10, 19))); + EXPECT_TRUE(!r.Contains(Point(15, 20))); + EXPECT_TRUE(!r.Contains(Point(10, 25))); + } END_TEST()