52 lines
1.5 KiB
C++
52 lines
1.5 KiB
C++
#include "Text.h"
|
|
#include <SDL3/SDL_init.h>
|
|
#include <cstdio>
|
|
|
|
|
|
SDL_AppResult Text::OpenFont(const fs::path &font) {
|
|
if (!TTF_Init()) {
|
|
SDL_Log("Couldn't initialize SDL_ttf: %s\n", SDL_GetError());
|
|
return SDL_APP_FAILURE;
|
|
}
|
|
|
|
loadedFont = TTF_OpenFont(fs::absolute(font).c_str(), 12.0f);
|
|
if (!loadedFont) {
|
|
printf("Font not found! \n");
|
|
return SDL_APP_FAILURE;
|
|
}
|
|
color = WHITE;
|
|
return SDL_APP_CONTINUE;
|
|
}
|
|
|
|
bool Text::SetText(const std::string &text, const Window *win, SDL_FRect rect) {
|
|
buffer += text;
|
|
|
|
SDL_DestroySurface(textRenderingSurface);
|
|
textRenderingSurface = TTF_RenderText_Blended(loadedFont, buffer.c_str(), 0, color);
|
|
|
|
if (textRenderingSurface) {
|
|
font_texture = SDL_CreateTextureFromSurface(win->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() const {
|
|
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, nullptr, &dst);
|
|
}
|