summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
author Vishnu Nair <vishnun@google.com> 2024-10-03 03:42:49 +0000
committer Vishnu Nair <vishnun@google.com> 2024-10-03 15:52:40 +0000
commitdfee5a2c360f4660dfad53bfd06d7923f98e242e (patch)
treec3aa5638ace0a392c72140e3230ab5e0a907dd53
parentf151262626f1c08a104cc35d9864493ea8a72dec (diff)
Fix rounding error when constructing Rect from FloatRect
Current rounding logic does not handle negative values correctly. FloatRect(-1080,...) is converted to Rect(-1079,...) Fix this by using the standard rounding function. Flag: EXEMPT build error (b/350967139) Bug: 310950423 Test: presubmit Change-Id: Ib8c5c393040149225e5b2bc858c21894e306a456
-rw-r--r--libs/ui/include/ui/Rect.h10
-rw-r--r--libs/ui/tests/Rect_test.cpp10
2 files changed, 14 insertions, 6 deletions
diff --git a/libs/ui/include/ui/Rect.h b/libs/ui/include/ui/Rect.h
index 2eb9330cc9..2307b44eb2 100644
--- a/libs/ui/include/ui/Rect.h
+++ b/libs/ui/include/ui/Rect.h
@@ -74,12 +74,10 @@ public:
}
inline explicit Rect(const FloatRect& floatRect) {
- // Ideally we would use std::round, but we don't want to add an STL
- // dependency here, so we use an approximation
- left = static_cast<int32_t>(floatRect.left + 0.5f);
- top = static_cast<int32_t>(floatRect.top + 0.5f);
- right = static_cast<int32_t>(floatRect.right + 0.5f);
- bottom = static_cast<int32_t>(floatRect.bottom + 0.5f);
+ left = static_cast<int32_t>(std::round(floatRect.left));
+ top = static_cast<int32_t>(std::round(floatRect.top));
+ right = static_cast<int32_t>(std::round(floatRect.right));
+ bottom = static_cast<int32_t>(std::round(floatRect.bottom));
}
inline explicit Rect(const ui::Size& size) {
diff --git a/libs/ui/tests/Rect_test.cpp b/libs/ui/tests/Rect_test.cpp
index 9cc36bb15b..c3c8bd9fa4 100644
--- a/libs/ui/tests/Rect_test.cpp
+++ b/libs/ui/tests/Rect_test.cpp
@@ -99,6 +99,16 @@ TEST(RectTest, constructFromFloatRect) {
EXPECT_EQ(30, rect.right);
EXPECT_EQ(40, rect.bottom);
}
+
+ EXPECT_EQ(Rect(0, 1, -1, 0), Rect(FloatRect(0.f, 1.f, -1.f, 0.f)));
+ EXPECT_EQ(Rect(100000, 100000, -100000, -100000),
+ Rect(FloatRect(100000.f, 100000.f, -100000.f, -100000.f)));
+
+ // round down if < .5
+ EXPECT_EQ(Rect(0, 1, -1, 0), Rect(FloatRect(0.4f, 1.1f, -1.499f, 0.1f)));
+
+ // round up if >= .5
+ EXPECT_EQ(Rect(20, 20, -20, -20), Rect(FloatRect(19.5f, 19.9f, -19.5f, -19.9f)));
}
TEST(RectTest, makeInvalid) {