Added Text.cpp

This commit is contained in:
2026-09-27 21:57:14 -05:00
parent 42c59530d3
commit 1a69261952
6 changed files with 105 additions and 33 deletions
+53
View File
@@ -0,0 +1,53 @@
#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);
}
+35
View File
@@ -0,0 +1,35 @@
#pragma once
#include <SDL3/SDL.h>
#include <SDL3/SDL_init.h>
#include <SDL3_ttf/SDL_textengine.h>
#include <SDL3_ttf/SDL_ttf.h>
#include <filesystem>
#include <string>
#include "fileCommon.h"
#include "window.h"
#define WHITE {255, 255, 255, SDL_ALPHA_OPAQUE}
class Text {
private:
std::string buffer;
TTF_Font *loadedFont = nullptr;
SDL_Surface *textRenderingSurface = nullptr;
SDL_Color color;
SDL_Texture *font_texture = nullptr;
/// ToDo: Replace with dynamic settings / loaded font
fs::path fontPath;
public:
SDL_AppResult OpenFont(fs::path fontPath);
bool SetText(std::string text, Window *window);
void Render();
void CloseFont() { TTF_CloseFont(loadedFont); }
};
+4 -2
View File
@@ -1,3 +1,5 @@
#pragma once
#include <SDL3/SDL.h>
#include <SDL3/SDL_init.h>
#include <SDL3/SDL_render.h>
@@ -14,8 +16,8 @@ public:
void Resize(int w, int h);
void Close();
SDL_Window *GetWindow() { return window; }
SDL_Renderer *GetRenderer() { return renderer; }
SDL_Window *GetWindow() const { return window; }
SDL_Renderer *GetRenderer() const { return renderer; }
};