Implement Point::Clamp(Rect)

This commit is contained in:
Dmitry Marakasov 2015-01-18 20:14:56 +03:00
parent 425b2f835f
commit 9d90792378
3 changed files with 52 additions and 0 deletions

View File

@ -21,6 +21,8 @@
#include <SDL2pp/Point.hh>
#include <SDL2pp/Rect.hh>
namespace SDL2pp {
Point::Point() {
@ -108,4 +110,22 @@ Point& Point::operator*=(int value) {
return *this;
}
Point Point::GetClamped(const Rect& rect) const {
Point p = *this;
p.Clamp(rect);
return p;
}
Point& Point::Clamp(const Rect& rect) {
if (x < rect.x)
x = rect.x;
if (x > rect.GetX2())
x = rect.GetX2();
if (y < rect.y)
y = rect.y;
if (y > rect.GetY2())
y = rect.GetY2();
return *this;
}
}

View File

@ -26,6 +26,8 @@
namespace SDL2pp {
class Rect;
////////////////////////////////////////////////////////////
/// \brief 2D point
///
@ -231,6 +233,26 @@ public:
///
////////////////////////////////////////////////////////////
Point& operator*=(int value);
////////////////////////////////////////////////////////////
/// \brief Get a point with coordinates modified so it fits into a given rect
///
/// \param[in] rect Rectangle to clamp with
///
/// \returns Clamped point
///
////////////////////////////////////////////////////////////
Point GetClamped(const Rect& rect) const;
////////////////////////////////////////////////////////////
/// \brief Clamp point coordinates to make it fit into a given rect
///
/// \param[in] rect Rectangle to clamp with
///
/// \returns Reference to self
///
////////////////////////////////////////////////////////////
Point& Clamp(const Rect& rect);
};
}

View File

@ -269,4 +269,14 @@ BEGIN_TEST()
EXPECT_TRUE(Rect(0, 2, 3, 4) != sdlrect);
EXPECT_TRUE(Point(0, 7) != sdlpoint);
}
{
// clamp
Rect rect(1, 2, 3, 4);
EXPECT_TRUE(Point(0, 0).GetClamped(rect) == Point(1, 2));
EXPECT_TRUE(Point(0, 0).Clamp(rect) == Point(1, 2));
EXPECT_TRUE(Point(10, 10).GetClamped(rect) == Point(3, 5));
EXPECT_TRUE(Point(10, 10).Clamp(rect) == Point(3, 5));
}
END_TEST()