Search code examples
sdl-2sdl-ttf

How do find out the width and height of the text without using surface in SDL2?


I wanted to create a separate function where I could just send a string and it will render the text appropriately so that I didn't need to copy-paste same stuff. The function I came up with is in the following.

void renderText(SDL_Renderer* renderer, char* text,
                char* font_name, int font_size,
                SDL_Color color, SDL_Rect text_area)
{
    /* If TTF was not initialized initialize it */
    if (!TTF_WasInit()) {
        if (TTF_Init() < 0) {
            printf("Error initializing TTF: %s\n", SDL_GetError());
            return EXIT_FAILURE;
        }
    }

    TTF_Font* font = TTF_OpenFont(font_name, font_size);
    if (font == NULL) {
        printf("Error opening font: %s\n", SDL_GetError());
        return;
    }

    SDL_Surface* surface = TTF_RenderText_Blended(font, text, color);
    SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surface);
    if (!texture) {
        printf("error creating texture: %s\n", SDL_GetError());
        TTF_CloseFont(font);
        return;
    }

    SDL_RenderCopy(renderer, message, NULL, &text_area);

    SDL_FreeSurface(surface);
    SDL_DestroyTexture(texture);
    TTF_CloseFont(font);

}

Now, sometimes I want to align the text with the window for which I need to know the height and width of the surface that contains the text so that I can use something like (WINDOW_WIDTH - surfaceText->w) / 2 or (WINDOW_HEIGHT - surfaceText->h) / 2. But there is no way to know the height and width of the surface containing the text without creating the surface. And if I end up needing to create the surface then the separation of this function would not live upto its objective.

How do I find out the height and width of the surface containing the text without actually creating the surface in SDL2_ttf library?


Solution

  • You can pass the string to the TTF_SizeText() function, which is defined:

    int TTF_SizeText(TTF_Font *font, const char *text, int *w, int *h)
    

    The documentation for this function states:

    Calculate the resulting surface size of the LATIN1 encoded text rendered using font. No actual rendering is done, however correct kerning is done to get the actual width. The height returned in h is the same as you can get using 3.3.10 TTF_FontHeight.

    Then, once you have the dimensions of the string, you can call your rendering function with the necessary information to align it.

    There are also TTF_SizeUTF8() and TTF_SizeUNICODE() versions for different encodings.