Hi, I seem to be hitting a weird issue on using SDL2_TTF on Mac OS, namely, the TTF_RenderText_Solid
call has to happen in the main event loop for rendering to work, even when the text to be rendered stays the same.
Here is a minimum example:
#include <SDL2/SDL.h>
#include <SDL2_ttf/SDL_ttf.h>
#include <stdlib.h>
#include <string>
#define WINDOW_WIDTH 300
#define WINDOW_HEIGHT (WINDOW_WIDTH)
/*
- x, y: upper left corner.
- texture, rect: outputs.
*/
void get_text_and_rect(SDL_Renderer *renderer, int x, int y, std::string text,
TTF_Font *font, SDL_Texture **texture, SDL_Rect *rect) {
int text_width;
int text_height;
SDL_Surface *surface;
SDL_Color textColor = {255, 255, 255, 0};
surface = TTF_RenderText_Solid(font, text.c_str(), textColor);
*texture = SDL_CreateTextureFromSurface(renderer, surface);
text_width = surface->w;
text_height = surface->h;
SDL_FreeSurface(surface);
rect->x = x;
rect->y = y;
rect->w = text_width;
rect->h = text_height;
}
int main(int argc, char **argv) {
SDL_Event event;
SDL_Rect rect1, rect2;
SDL_Renderer *renderer;
SDL_Texture *texture1, *texture2;
SDL_Window *window;
std::string font_path;
int quit;
font_path = "path-to-font.ttf";
/* Inint TTF. */
SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO);
SDL_CreateWindowAndRenderer(WINDOW_WIDTH, WINDOW_WIDTH, 0, &window,
&renderer);
TTF_Init();
TTF_Font *font = TTF_OpenFont(font_path.c_str(), 24);
if (font == NULL) {
fprintf(stderr, "error: font not found\n");
exit(EXIT_FAILURE);
}
quit = 0;
// Does not work unless these two lines below are in the main while loop
get_text_and_rect(renderer, 0, 0, "hello", font, &texture1, &rect1);
get_text_and_rect(renderer, 0, rect1.y + rect1.h, "world", font, &texture2,
&rect2);
while (!quit) {
while (SDL_PollEvent(&event) == 1) {
if (event.type == SDL_QUIT) {
quit = 1;
}
}
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0);
SDL_RenderClear(renderer);
// Would work if the get_text_and_rect calls are placed here
/* Use TTF textures. */
SDL_RenderCopy(renderer, texture1, NULL, &rect1);
SDL_RenderCopy(renderer, texture2, NULL, &rect2);
SDL_RenderPresent(renderer);
}
/* Deinit TTF. */
SDL_DestroyTexture(texture1);
SDL_DestroyTexture(texture2);
TTF_Quit();
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return EXIT_SUCCESS;
}
As commented in code, I have to move the get_text_and_rect
call inside the main event loop for it to render the text. This seems to not be the case from all the sdl tutorials I’ve read (for example: LazyFoo’s tutorial). While I could work around by placing them in the main loop, it is very inefficient as the text does not change.
Is this a known issue? I’m on BigSur 11.2.3 and SDL_ttf 2.0.15
Thanks!