Skip to content

Not possible to center text, TTF_GetTextSize returns wrong size #555

@aandrejevas

Description

@aandrejevas

I suspect TTF_GetTextSize is returning wrong size because I was not able to center text.
Code:

#define SDL_MAIN_USE_CALLBACKS true
#include <SDL3/SDL.h>
#include <SDL3/SDL_main.h>
#include <SDL3_ttf/SDL_ttf.h>

SDL_Window * window;
SDL_Renderer * renderer;
TTF_Font * font;
TTF_TextEngine * text_engine;
TTF_Text * text_object;

SDL_AppResult SDL_AppInit(void ** const, const int, char ** const) {
	SDL_SetHint(SDL_HINT_MAIN_CALLBACK_RATE, "10");
	TTF_Init();
	SDL_CreateWindowAndRenderer("test", 0, 0, SDL_WINDOW_FULLSCREEN, &window, &renderer);

	font = TTF_OpenFont("Ruler Stencil Heavy.ttf", 980);
	text_engine = TTF_CreateRendererTextEngine(renderer);
	text_object = TTF_CreateText(text_engine, font, "Ačiū", 0);

	return SDL_AppResult::SDL_APP_CONTINUE;
}

SDL_AppResult SDL_AppEvent(void * const, SDL_Event * const event) {
	switch (event->type) {
	case SDL_EventType::SDL_EVENT_QUIT:
		return SDL_AppResult::SDL_APP_SUCCESS;

	case SDL_EventType::SDL_EVENT_KEY_DOWN:
		switch (event->key.key) {
		case SDLK_ESCAPE:
			return SDL_AppResult::SDL_APP_SUCCESS;
		}
		break;
	}
	return SDL_AppResult::SDL_APP_CONTINUE;
}

SDL_AppResult SDL_AppIterate(void * const) {
	int window_width, window_height, text_width, text_height;
	SDL_GetWindowSizeInPixels(window, &window_width, &window_height);
	TTF_GetTextSize(text_object, &text_width, &text_height);
	TTF_DrawRendererText(text_object, (window_width - text_width) / 2, (window_height - text_height) / 2);

	SDL_RenderPresent(renderer);
	return SDL_AppResult::SDL_APP_CONTINUE;
}

void SDL_AppQuit(void * const, const SDL_AppResult) {
	TTF_Quit();
}

What is rendered:
Image
As can be seen, on the left the letter A is cut off and on the right the letter ū does not reach the edge. Also the text is not vertically aligned. That means that the text is not centered and that means that TTF_GetTextSize returned wrong size.

Font (github does not let me add a .ttf file):
https://www.dafont.com/ruler-stencil.font

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions