简体   繁体   中英

How to automatically adjust width for text with SDL2_TTF

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM