#include "text.h" Text* Text_init(int posX, int posY, const FcChar8 *TEXT_FONT_STYLE, int TEXT_FONT_PTSIZE) { Text *t = malloc(sizeof(Text)); *(int *)&t->POSX = posX; *(int *)&t->POSY = posY; FcConfig *config = FcInitLoadConfigAndFonts(); FcPattern *pat = FcPatternCreate(); FcObjectSet* os = FcObjectSetBuild (FC_FAMILY, FC_STYLE, FC_LANG, FC_FILE, (char *) 0); FcFontSet* fs = FcFontList(config, pat, os); FcChar8 *style, *family; for (int i=0; fs && i < fs->nfont; ++i) { FcPattern* font = fs->fonts[i]; if (FcPatternGetString(font, FC_FILE, 0, &(t->TEXT_FONT_FILE)) == FcResultMatch && FcPatternGetString(font, FC_FAMILY, 0, &family) == FcResultMatch && FcPatternGetString(font, FC_STYLE, 0, &style) == FcResultMatch && strcmp(TEXT_FONT_FAMILY, family) == 0 && strcmp(TEXT_FONT_STYLE, style) == 0) { break; } } t->TEXT_FONT = TTF_OpenFont(t->TEXT_FONT_FILE, TEXT_FONT_PTSIZE); FcFontSetDestroy(fs); FcObjectSetDestroy(os); FcPatternDestroy(pat); FcConfigDestroy(config); if (t->TEXT_FONT == NULL) { printf("TTF_OpenFont fail with path '%s'. TTF_Error: %s\n", t->TEXT_FONT_FILE, TTF_GetError()); free(t); return NULL; } return t; } void Text_free(Text *t) { TTF_CloseFont(t->TEXT_FONT); free(t); } int Text_render(const Text* t, SDL_Renderer *renderer, const char *str, int width, int height) { SDL_Rect textRect = { t->POSX , t->POSY, width, height }; SDL_Surface *textSurface = TTF_RenderText_Solid(t->TEXT_FONT, str, TEXT_FONT_COLOR); if (textSurface == NULL) { printf("Text rendering failed. TTF_Error: %s\n", TTF_GetError()); return 1; } SDL_Texture *textTexture = SDL_CreateTextureFromSurface(renderer, textSurface); if (textTexture == NULL) { printf("Texture rendering failed. SDL_Error: %s\n", SDL_GetError()); SDL_FreeSurface(textSurface); return 1; } SDL_RenderCopy(renderer, textTexture, NULL, &textRect); SDL_FreeSurface(textSurface); SDL_DestroyTexture(textTexture); return 0; }