Fixed text alignment to be visible based rather than surface based

This commit is contained in:
2025-12-08 17:16:46 +02:00
parent 8e88adf1df
commit 9f8a037f69
3 changed files with 87 additions and 9 deletions

View File

@@ -15,6 +15,72 @@ static SDL_Surface* render_text(bool should_wrap, TTF_Font* font, const string&
return txt_surface;
}
static SDL_Rect find_visible_area(const SDL_Surface* txt_surface)
{
int x_start = -1;
int x_end = -1;
int y_start = -1;
int y_end = -1;
for (int y = 0; y < txt_surface->h; ++y)
{
bool found = false;
for (int x = 0; x < txt_surface->w; ++x)
{
if (1 == (static_cast<Uint8*>(txt_surface->pixels)[y * txt_surface->pitch + x]))
{
if (-1 == x_start)
{
x_start = x;
}
else
{
if (x < x_start)
{
x_start = x;
}
}
if (-1 == x_end)
{
x_end = x;
}
else
{
if (x > x_end)
{
x_end = x;
}
}
found = true;
}
}
if (found)
{
if (-1 == y_start)
{
y_start = y;
}
y_end = y;
}
}
SDL_Rect result = {.x = 0, .y = 0, .w = 0, .h = 0};
if ((-1 != x_start) && (-1 != x_end))
{
result.x = x_start;
result.w = x_end - x_start + 1;
}
if ((-1 != y_start) && (-1 != y_end))
{
result.y = y_start;
result.h = y_end - y_start + 1;
}
return result;
}
WidgetText::WidgetText(int x, int y, int width, int height, string text,
TextFit fit, bool should_wrap,
HorizontalAlign halign, VerticalAlign valign,
@@ -171,7 +237,8 @@ void WidgetText::draw()
}
// Now we have the final rendered text surface
SDL_Rect align = surface_align(m_surface, txt_surface, m_halign, m_valign);
SDL_Rect hint = find_visible_area(txt_surface);
SDL_Rect align = surface_align(m_surface, txt_surface, m_halign, m_valign, &hint);
SDL_BlitSurface(txt_surface, NULL, m_surface, &align);
SDL_FreeSurface(txt_surface);
}