Fixed automatic text resizing (both auto and shrink)

This commit is contained in:
2026-04-03 16:22:53 +03:00
parent 5535bfe290
commit 7b13f45bd3

View File

@@ -172,6 +172,7 @@ void WidgetText::set_halign_via_visible(bool value)
{ {
m_halign_via_visible = value; m_halign_via_visible = value;
} }
void WidgetText::set_valign_via_visible(bool value) void WidgetText::set_valign_via_visible(bool value)
{ {
m_valign_via_visible = value; m_valign_via_visible = value;
@@ -179,6 +180,7 @@ void WidgetText::set_valign_via_visible(bool value)
void WidgetText::draw() void WidgetText::draw()
{ {
int current_text_size = m_size;
if (nullptr == m_surface) if (nullptr == m_surface)
{ {
return; return;
@@ -193,7 +195,7 @@ void WidgetText::draw()
font_name = default_font_name; 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) if (nullptr == font)
{ {
// TODO: Message printing // TODO: Message printing
@@ -209,40 +211,42 @@ void WidgetText::draw()
return; return;
} }
// Check if text fits // Enlarge text until it becomes too big
if (m_fit != FIT_NONE) if (FIT_AUTO == m_fit)
{ {
double x_scale; while ((txt_surface->w < m_surface->w) && (txt_surface->h < m_surface->h))
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)
{ {
min_scale = y_scale; // Increase 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 // Re-render text
if (new_text_size != m_size)
{
SDL_FreeSurface(txt_surface); 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
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)
{
while ((txt_surface->w > m_surface->w) || (txt_surface->h > m_surface->h))
{
// Decrease 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) if (nullptr == font)
{ {
// TODO: Message printing // TODO: Message printing