From 7b13f45bd3a1e564e81927ead5fff58118ca2847 Mon Sep 17 00:00:00 2001 From: nedko Date: Fri, 3 Apr 2026 16:22:53 +0300 Subject: [PATCH] Fixed automatic text resizing (both auto and shrink) --- Widgets/WidgetText.cpp | 64 ++++++++++++++++++++++-------------------- 1 file changed, 34 insertions(+), 30 deletions(-) diff --git a/Widgets/WidgetText.cpp b/Widgets/WidgetText.cpp index 8438a6c..5e94773 100644 --- a/Widgets/WidgetText.cpp +++ b/Widgets/WidgetText.cpp @@ -172,6 +172,7 @@ void WidgetText::set_halign_via_visible(bool value) { m_halign_via_visible = value; } + void WidgetText::set_valign_via_visible(bool value) { m_valign_via_visible = value; @@ -179,6 +180,7 @@ void WidgetText::set_valign_via_visible(bool value) void WidgetText::draw() { + int current_text_size = m_size; if (nullptr == m_surface) { return; @@ -193,7 +195,7 @@ void WidgetText::draw() font_name = default_font_name; } - TTF_Font* font = get_font(m_size, font_name); + TTF_Font* font = get_font(current_text_size, font_name); if (nullptr == font) { // TODO: Message printing @@ -209,40 +211,42 @@ void WidgetText::draw() return; } - // Check if text fits + // Enlarge text until it becomes too big + if (FIT_AUTO == m_fit) + { + while ((txt_surface->w < m_surface->w) && (txt_surface->h < m_surface->h)) + { + // Increase size and try again + ++current_text_size; + + // Re-render text + SDL_FreeSurface(txt_surface); + font = get_font(current_text_size, font_name); + if (nullptr == font) + { + // TODO: Message printing + return; + } + txt_surface = render_text(m_should_wrap, font, m_text, m_text_color, m_rect.w); + if (nullptr == txt_surface) + { + // TODO: Message printing + return; + } + } + } + + // Shrink if it doesn't fit if (m_fit != FIT_NONE) { - double x_scale; - double y_scale; - - x_scale = m_surface->w; - x_scale /= txt_surface->w; - - y_scale = m_surface->h; - y_scale /= txt_surface->h; - - // Find the scale needed to shrink or enlarge with - double min_scale = x_scale; - if (y_scale < min_scale) + while ((txt_surface->w > m_surface->w) || (txt_surface->h > m_surface->h)) { - min_scale = y_scale; - } + // Decrease size and try again + --current_text_size; - // Do not scale up if only shrinkage is allowed - if ((min_scale > 1.0) && (FIT_SHRINK == m_fit)) - { - min_scale = 1.0; - } - - // Find new font size - int new_text_size = m_size; - new_text_size *= min_scale; - - // Re-render text - if (new_text_size != m_size) - { + // Re-render text SDL_FreeSurface(txt_surface); - font = get_font(new_text_size, font_name); + font = get_font(current_text_size, font_name); if (nullptr == font) { // TODO: Message printing