I'm trying to display the string "hey" using a true type font in SDL, but there are glitches. Here is the text as it should appear (I took a screen recording, so the lower part in this shot is just the control for the video player):
And here it is with a glitch:
As you can see the upper part of the letter "h" is missing.
Here is the code that I used:
#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>
#include <iostream>
#include <string>
int fatal( std::string m ) {
std::cout << "Fatal error: " << m << "\n";
exit(-1);
}
void drawText(TTF_Font* font,SDL_Renderer* r, std::string message) {
SDL_Color c = {255,255,255,255};
SDL_Surface *temp = TTF_RenderText_Blended( font, message.c_str(), c);
if ( temp == NULL )
fatal("failed to create surface");
SDL_Texture *txt = SDL_CreateTextureFromSurface( r, temp );
if ( txt == NULL )
fatal("failed to create texture");
SDL_FreeSurface( temp );
SDL_Rect src;
src.x = 0;
src.y = 0;
SDL_QueryTexture( txt, NULL, NULL, &src.w, &src.h );
SDL_Rect pos;
pos.x = 80;
pos.y = 80;
pos.w = src.w;
pos.h = src.h;
if ( SDL_RenderCopy(r,txt,&src,&pos) != 0)
fatal("SDL_RenderCopy failed");
SDL_DestroyTexture(txt);
}
extern "C" int main( int argc, char** argv ) {
SDL_Renderer *renderer;
SDL_Window *window;
if ( SDL_Init( SDL_INIT_VIDEO ) != 0 )
fatal("sdl_init failed");
if ( TTF_Init() != 0 )
fatal("ttf_init failed");
if ( SDL_CreateWindowAndRenderer ( 200, 200, 0, &window, &renderer ) != 0 )
fatal("sdl_createwindowandrenderer failed");
TTF_Font* font = TTF_OpenFont( "Arial.ttf", 30 );
if ( font == NULL )
fatal("failed to open font");
SDL_Event e;
while ( 1 ) {
if ( SDL_PollEvent(&e) ) {
if (e.type == SDL_QUIT)
break;
}
// clear back buffer
SDL_SetRenderDrawColor(renderer,0,0,255,255);
SDL_RenderClear(renderer);
drawText(font,renderer,"hey");
SDL_RenderPresent(renderer);
}
return 0;
}
Which I compiled on macOS 10.15.6 using the following command
g++ -std=c++17 textTest.cpp -lSDL2 -lSDL2_ttf