Skip to content

Commit 688c257

Browse files
committed
Add snapToInt() method to Rect
Resolves: #528
1 parent c6f7e47 commit 688c257

File tree

3 files changed

+33
-0
lines changed

3 files changed

+33
-0
lines changed

include/scratchcpp/rect.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@ class LIBSCRATCHCPP_EXPORT Rect
3232
double width() const;
3333
double height() const;
3434

35+
void snapToInt();
36+
3537
bool intersects(const Rect &rect) const;
3638

3739
private:

src/rect.cpp

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,16 @@ double Rect::height() const
7878
return std::abs(impl->top - impl->bottom);
7979
}
8080

81+
/*! Push out the rectangle to integer bounds. */
82+
void Rect::snapToInt()
83+
{
84+
// https://github.com/scratchfoundation/scratch-render/blob/c3ede9c3d54769730c7b023021511e2aba167b1f/src/Rectangle.js#L136-L141
85+
impl->left = std::floor(impl->left);
86+
impl->right = std::ceil(impl->right);
87+
impl->bottom = std::floor(impl->bottom);
88+
impl->top = std::ceil(impl->top);
89+
}
90+
8191
/*! Returns true if the rectangle intersects the given rectangle. */
8292
bool Rect::intersects(const Rect &rect) const
8393
{

test/rect/rect_test.cpp

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,27 @@ TEST(RectTest, Height)
7878
ASSERT_EQ(rect.height(), 35.272);
7979
}
8080

81+
TEST(RectTest, SnapToInt)
82+
{
83+
{
84+
Rect rect(20.5, 12.5, 22.5, 8.5);
85+
rect.snapToInt();
86+
ASSERT_EQ(rect.left(), 20);
87+
ASSERT_EQ(rect.top(), 13);
88+
ASSERT_EQ(rect.right(), 23);
89+
ASSERT_EQ(rect.bottom(), 8);
90+
}
91+
92+
{
93+
Rect rect(20.5, 12.2, 22.3, 8.5);
94+
rect.snapToInt();
95+
ASSERT_EQ(rect.left(), 20);
96+
ASSERT_EQ(rect.top(), 13);
97+
ASSERT_EQ(rect.right(), 23);
98+
ASSERT_EQ(rect.bottom(), 8);
99+
}
100+
}
101+
81102
TEST(RectTest, Intersects)
82103
{
83104
Rect rect1(-50, 25, 150, -75);

0 commit comments

Comments
 (0)