From af439cf3af3aa5e72992f17b3adbd301ff4f136d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?kleines=20Filmr=C3=B6llchen?= Date: Fri, 21 Oct 2022 17:05:20 +0200 Subject: [PATCH] LibGfx: Add Size::match_aspect_ratio This will create a size that matches the given aspect ratio while preserving one of the two dimensions. --- Userland/Libraries/LibGfx/Size.h | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/Userland/Libraries/LibGfx/Size.h b/Userland/Libraries/LibGfx/Size.h index 200e764c5e..16f3a623e6 100644 --- a/Userland/Libraries/LibGfx/Size.h +++ b/Userland/Libraries/LibGfx/Size.h @@ -93,6 +93,25 @@ public: return static_cast(width()) / static_cast(height()); } + // Horizontal means preserve the width, Vertical means preserve the height. + [[nodiscard]] constexpr Size match_aspect_ratio(float aspect_ratio, Orientation side_to_preserve) const + { + VERIFY(aspect_ratio != 0.0f); + auto matched = *this; + auto height_corresponding_to_width = static_cast(static_cast(width()) / aspect_ratio); + auto width_corresponding_to_height = static_cast(static_cast(height()) * aspect_ratio); + + switch (side_to_preserve) { + case Orientation::Vertical: + matched.m_width = width_corresponding_to_height; + break; + case Orientation::Horizontal: + matched.m_height = height_corresponding_to_width; + break; + } + return matched; + } + template [[nodiscard]] constexpr bool contains(Size const& other) const {