This commit is contained in:
2025-04-23 22:55:22 +02:00
commit 8fd5f1cf1e
8 changed files with 565 additions and 0 deletions

61
util/font.c Normal file
View File

@@ -0,0 +1,61 @@
//
// Created by bruno on 1.2.2025.
//
#include "font.h"
BitmapFont
prepText(SDL_Renderer *renderer, unsigned char pxSize, const char *file, uint8_t r, uint8_t g, uint8_t b, uint8_t a) {
TTF_Font *gFont = TTF_OpenFont(file, pxSize);
BitmapFont out;
out.size = pxSize;
out.color = (SDL_Color) {r, g, b, a};
unsigned int i = 1;
do {
if (i == 173) { //specifically this char is 0 width (IDK why)
out.surface[i] = SDL_CreateRGBSurface(0, pxSize, pxSize, 32, 0, 0, 0, 0);
} else {
char tmpOut[2] = {i, 0};
out.surface[i] = TTF_RenderText_Solid(gFont, tmpOut, out.color);
}
out.texture[i] = SDL_CreateTextureFromSurface(renderer, out.surface[i]);
i++;
} while (i < 256);
TTF_CloseFont(gFont);
return out;
}
void renderText(SDL_Renderer *renderer, BitmapFont font, char *string, uint16_t x, uint16_t y) {
SDL_Rect charRect;
charRect.x = 0;
charRect.y = 0;
charRect.w = font.size;
charRect.h = font.size;
SDL_Rect outRect = charRect;
outRect.x = x;
outRect.y = y;
while (*string) {
if (*string == '\n') {
outRect.x = x;
outRect.y += charRect.h + 4;
string++;
continue;
}
SDL_RenderCopy(renderer, font.texture[*string], &charRect, &outRect);
outRect.x += charRect.w + 1;
string++;
}
}
void destroyFont(BitmapFont *font) {
for (uint16_t i = 1; i < 256; i++) {
if (font->texture[i]) {
SDL_DestroyTexture(font->texture[i]);
}
if (font->surface[i]) {
SDL_FreeSurface(font->surface[i]);
}
}
}