I'm working on a score display for my simple 2d SDL_2 Game.
This is the part of my code where I display the speed (basically just score):
void Renderer::renderText(const char* text, SDL_Rect* destR)
{
SDL_Surface* surfaceText = TTF_RenderText_Solid(Renderer::font, text, { 255,255,255 });
SDL_Texture* textureText = SDL_CreateTextureFromSurface(renderer, surfaceText);
SDL_FreeSurface(surfaceText);
SDL_RenderCopy(renderer, textureText, NULL, destR);
SDL_DestroyTexture(textureText);
}
There is the obvious problem that if I have a width for the number "1", the text would be squished a lot of the number was "10000" etc as you would have to fit 5 characters into an SDL_Rect that is only 1 character wide.
I could multiply the width by the number of characters however that wouldn't be very accurate as different characters have different widths.
How would I solve this?
(I only answered this because I found out how and nobody else answered)
You can do something like this.
SDL_Rect destR = { x, y, 0, 0 };
TTF_SizeText(font, text, &destR.w, &destR.h);
Basically, TTF_SizeText enables you to get the native width and height from the text with font. Then you can just multiply the height and width as you wish.