Browse Source

Implement x-align for wrapped TTF text

pull/314/head
Gleb Mazovetskiy 7 years ago committed by Anders Jenbo
parent
commit
40651d8a19
  1. 14
      SourceX/DiabloUI/text_draw.cpp
  2. 14
      SourceX/DiabloUI/ttf_render_wrapped.cpp
  3. 8
      SourceX/DiabloUI/ttf_render_wrapped.h

14
SourceX/DiabloUI/text_draw.cpp

@ -12,6 +12,15 @@ extern SDL_Surface *pal_surface;
namespace {
TextAlignment XAlignmentFromFlags(int flags)
{
if (flags & UIS_CENTER)
return TextAlignment::CENTER;
if (flags & UIS_RIGHT)
return TextAlignment::END;
return TextAlignment::BEGIN;
}
int AlignXOffset(int flags, const SDL_Rect &dest, int w)
{
if (flags & UIS_CENTER)
@ -29,8 +38,9 @@ void DrawTTF(const char *text, const SDL_Rect &rect, int flags,
{
if (*render_cache == nullptr) {
*render_cache = new TtfSurfaceCache();
(*render_cache)->text = RenderUTF8_Solid_Wrapped(font, text, text_color, rect.w);
(*render_cache)->shadow = RenderUTF8_Solid_Wrapped(font, text, shadow_color, rect.w);
const auto x_align = XAlignmentFromFlags(flags);
(*render_cache)->text = RenderUTF8_Solid_Wrapped(font, text, text_color, rect.w, x_align);
(*render_cache)->shadow = RenderUTF8_Solid_Wrapped(font, text, shadow_color, rect.w, x_align);
}
SDL_Surface *text_surface = (*render_cache)->text;
SDL_Surface *shadow_surface = (*render_cache)->shadow;

14
SourceX/DiabloUI/ttf_render_wrapped.cpp

@ -19,7 +19,7 @@ SDL_bool CharacterIsDelimiter(char c, const char *delimiters)
} // namespace
// Based on SDL 2.0.12 TTF_RenderUTF8_Blended_Wrapped
SDL_Surface *RenderUTF8_Solid_Wrapped(TTF_Font *font, const char *text, SDL_Color fg, Uint32 wrapLength)
SDL_Surface *RenderUTF8_Solid_Wrapped(TTF_Font *font, const char *text, SDL_Color fg, Uint32 wrapLength, TextAlignment x_align)
{
int width, height;
SDL_Surface *textbuf;
@ -142,6 +142,18 @@ SDL_Surface *RenderUTF8_Solid_Wrapped(TTF_Font *font, const char *text, SDL_Colo
SDL_Surface *tmp = TTF_RenderUTF8_Solid(font, text, fg);
dest.w = static_cast<decltype(SDL_Rect().w)>(tmp->w);
dest.h = static_cast<decltype(SDL_Rect().h)>(tmp->h);
switch (x_align) {
case TextAlignment::END:
dest.x = textbuf->w - tmp->w;
break;
case TextAlignment::CENTER:
dest.x = (textbuf->w - tmp->w) / 2;
break;
case TextAlignment::BEGIN:
dest.x = 0;
break;
}
SDL_BlitSurface(tmp, nullptr, textbuf, &dest);
dest.y += tmp->h;
SDL_FreeSurface(tmp);

8
SourceX/DiabloUI/ttf_render_wrapped.h

@ -6,9 +6,15 @@
namespace dvl {
enum class TextAlignment {
BEGIN = 0,
CENTER,
END,
};
// `TTF_RenderUTF8_Solid_Wrapped` is only available in SDL2 2.0.16 (unreleased
// as of this writing). This is a hacky alternative.
SDL_Surface *RenderUTF8_Solid_Wrapped(
TTF_Font *font, const char *text, SDL_Color fg, Uint32 wrapLength);
TTF_Font *font, const char *text, SDL_Color fg, Uint32 wrapLength, TextAlignment x_align = TextAlignment::BEGIN);
} // namespace dvl

Loading…
Cancel
Save