Files
Text-Adventure/ui/Text.cpp
T
2026-09-27 21:57:14 -05:00

54 lines
1.4 KiB
C++

#include "Text.h"
#include <SDL3/SDL_init.h>
#include <cstdio>
SDL_AppResult Text::OpenFont(fs::path fontPath) {
if (!TTF_Init()) {
SDL_Log("Couldn't initialize SDL_ttf: %s\n", SDL_GetError());
return SDL_APP_FAILURE;
}
loadedFont = TTF_OpenFont(fs::absolute(fontPath).c_str(), 12.0f);
if (!loadedFont) {
printf("Font not found! \n");
return SDL_APP_FAILURE;
}
color = WHITE;
return SDL_APP_CONTINUE;
}
bool Text::SetText(std::string text, Window *window) {
buffer += text;
SDL_DestroySurface(textRenderingSurface);
textRenderingSurface = TTF_RenderText_Blended(loadedFont, buffer.c_str(), 0, color);
if (textRenderingSurface) {
font_texture = SDL_CreateTextureFromSurface(window->GetRenderer(), textRenderingSurface);
SDL_DestroySurface(textRenderingSurface);
}
if (!font_texture) {
SDL_Log("Couldn't create text: %s\n", SDL_GetError());
return false;
}
return true;
}
void Text::Render() {
int w = 0, h = 0;
SDL_FRect dst;
const float scale = 4.0f;
/* Center the text and scale it up */
SDL_GetRenderOutputSize(window.GetRenderer(), &w, &h);
SDL_SetRenderScale(window.GetRenderer(), scale, scale);
SDL_GetTextureSize(font_texture, &dst.w, &dst.h);
dst.x = ((w / scale) - dst.w) / 2;
dst.y = ((h / scale) - dst.h) / 2;
SDL_RenderTexture(window.GetRenderer(), font_texture, NULL, &dst);
}