Search code examples
c++sdlsdl-2

Problem with height and width for displaying Text with SDL 2


I have a problem for displaying text in SDL2. The text look weird with Message_rect.w = 100 and Message_rect.h = 100. I change manually change that, but it's not automatic. Do you know how can I automatically know the perfect height and width for text ?

This is my actually code :

TTF_Font* Sans = TTF_OpenFont("asset/arial.ttf", 24);
SDL_Color White = {255, 255, 255, 0};
SDL_Surface* surfaceMessage = TTF_RenderText_Solid(Sans, "put your text here", White);
SDL_Texture* Message = SDL_CreateTextureFromSurface(renderer, surfaceMessage);
SDL_Rect Message_rect;
Message_rect.x = 600;
Message_rect.y = 200;
Message_rect.w = 100;
Message_rect.h = 100;
SDL_RenderCopy(renderer, Message, NULL, &Message_rect);
SDL_FreeSurface(surfaceMessage);
SDL_DestroyTexture(Message);

Solution

  • I found the answer, I just have to give my Message_rect to the 'SDL_GetClipRect' function. So the code is now :

    TTF_Font* Sans = TTF_OpenFont("asset/arial.ttf", 24);
    SDL_Color White = {255, 255, 255, 0};
    SDL_Surface* surfaceMessage = TTF_RenderText_Solid(Sans, "This is a good test", White);
    SDL_Texture* Message = SDL_CreateTextureFromSurface(renderer, surfaceMessage);
    SDL_Rect Message_rect;
    SDL_GetClipRect(surfaceMessage, &Message_rect);
    Message_rect.x = 600;
    Message_rect.y = 200;
    SDL_RenderCopy(renderer, Message, NULL, &Message_rect);
    SDL_FreeSurface(surfaceMessage);
    SDL_DestroyTexture(Message);