Logo Glusoft
Become a Patron! Buy me a coffee!

Displaying unicode text with SDL_ttf

Unicode text with SDL2

The first thing to do is initialize SDL and SDL_ttf create the window and the renderer:


SDL_Window *window = NULL;
SDL_Renderer *renderer = NULL;
SDL_CreateWindowAndRenderer(400, 300, 0, &window, &renderer);

To display the random text in japanese we need to use wstring.
std::wstring text = L"申し訳ございませんがたくさんあります。\n忘れている世界によって忘れている世界。\n汚れのない心の永遠の日差し!\nそれぞれの祈りが受け入れられ、それぞれが辞任を望む";

After that we will use the japanese font: KosugiMaru-Regular.ttf
TTF_Font *kosugi = TTF_OpenFont("KosugiMaru-Regular.ttf", 16);

To render the end of the line '\n' we need to use TTF_RenderUNICODE_Blended_Wrapped, the wstring need to be cast into const Uint16*
SDL_Surface *sur = TTF_RenderUNICODE_Blended_Wrapped(kosugi, (const Uint16*) text.c_str(), SDL_Color{ 255, 255, 255, 255 }, 300);

To have nice kanji I use the rendering blended, but you can use TTF_RenderUNICODE_Shaded or TTF_RenderUNICODE_Solid if you want something faster.
We need to keep track of the size of the surface, we will use it after to render the texture.
SDL_Rect rect{ 50, 100, sur->w, sur->h };
Then create the texture and free the surface.
SDL_Texture *tex = SDL_CreateTextureFromSurface(renderer, sur);

The event loop with the rendering is pretty standard:
SDL_Event event;
bool done = false;

while (!done) {
	while (SDL_PollEvent(&event)) {
		if (event.type == SDL_KEYDOWN) {
			if (event.key.keysym.scancode == SDL_SCANCODE_ESCAPE) {
				done = 1;

	SDL_RenderCopy(renderer, tex, NULL, &rect);

Then free all the resources allocated and terminate the program.

return 0;

You can download the project: DisplayTexts.7z
Post Comments
Dark theme