From 5fd6be2f64d4c5ad37afea0f415c715b1bec5f1d Mon Sep 17 00:00:00 2001 From: Vadim Zeitlin Date: Wed, 10 May 2023 00:09:41 +0100 Subject: [PATCH] Add wxRect::MakeCenteredIn() modifying the rectangle in place This can be more convenient than calling CenterIn(). --- include/wx/gdicmn.h | 15 ++++++++++++--- interface/wx/gdicmn.h | 16 ++++++++++++++++ tests/geometry/rect.cpp | 4 ++++ 3 files changed, 32 insertions(+), 3 deletions(-) diff --git a/include/wx/gdicmn.h b/include/wx/gdicmn.h index 46de754f82..236ba350ee 100644 --- a/include/wx/gdicmn.h +++ b/include/wx/gdicmn.h @@ -848,11 +848,20 @@ public: // centre this rectangle in the given (usually, but not necessarily, // larger) one + void MakeCenteredIn(const wxRect& r, int dir = wxBOTH) + { + if ( dir & wxHORIZONTAL ) + x = r.x + (r.width - width)/2; + if ( dir & wxVERTICAL ) + y = r.y + (r.height - height)/2; + } + + // same as above but returns the new rectangle instead of modifying this one wxRect CentreIn(const wxRect& r, int dir = wxBOTH) const { - return wxRect(dir & wxHORIZONTAL ? r.x + (r.width - width)/2 : x, - dir & wxVERTICAL ? r.y + (r.height - height)/2 : y, - width, height); + wxRect rect(*this); + rect.MakeCenteredIn(r, dir); + return rect; } wxRect CenterIn(const wxRect& r, int dir = wxBOTH) const diff --git a/interface/wx/gdicmn.h b/interface/wx/gdicmn.h index 383a0f6307..822c338a67 100644 --- a/interface/wx/gdicmn.h +++ b/interface/wx/gdicmn.h @@ -307,6 +307,8 @@ public: centred in both directions but if @a dir includes only @c wxVERTICAL or only @c wxHORIZONTAL, then it is only centered in this direction while the other component of its position remains unchanged. + + @see MakeCenteredIn() */ wxRect CentreIn(const wxRect& r, int dir = wxBOTH) const; wxRect CenterIn(const wxRect& r, int dir = wxBOTH) const; @@ -475,6 +477,20 @@ public: */ bool IsEmpty() const; + /** + Center this rectangle inside the given rectangle @a r. + + By default, rectangle is centred in both directions but if @a dir + includes only @c wxVERTICAL or only @c wxHORIZONTAL, then it is only + centered in this direction while the other component of its position + remains unchanged. + + @see CenterIn() + + @since 3.3.0 + */ + void MakeCenteredIn(const wxRect& r, int dir = wxBOTH); + ///@{ /** Moves the rectangle by the specified offset. If @a dx is positive, the diff --git a/tests/geometry/rect.cpp b/tests/geometry/rect.cpp index 1105e177c3..bbb473d024 100644 --- a/tests/geometry/rect.cpp +++ b/tests/geometry/rect.cpp @@ -31,6 +31,10 @@ TEST_CASE("wxRect::CentreIn", "[rect]") CHECK( R(0, 0, 10, 10).CentreIn(R(0, 0, 100, 100)) == R(45, 45, 10, 10) ); CHECK( R(0, 0, 20, 20).CentreIn(R(0, 0, 10, 10)) == R(-5, -5, 20, 20) ); + + R r(-10, -10, 20, 20); + r.MakeCenteredIn(R(0, 0, 100, 100), wxHORIZONTAL); + CHECK( r == R(40, -10, 20, 20) ); } TEST_CASE("wxRect::InflateDeflate", "[rect]")