Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

SDL2 TTF is a library that allows the use of TrueType fonts in SDL2 applications. Follow these steps to display text on a window using SDL2 TTF:

  1. Install the SDL2 TTF library and include the necessary header files in your project.

  2. Initialize SDL2 TTF. This can be done using the TTF_Init() function.

  3. Load the font you want to use with the TTF_OpenFont() function. This function takes the font file name and font size as input parameters.

  4. Create an SDLSurface to hold the text. This can be done using the TTFRenderText_Solid() function.

  5. Create an SDLTexture from the surface with the SDLCreateTextureFromSurface() function.

  6. Render the texture to the window using the SDL_RenderCopy() function.

  7. Free the surface and texture, and close SDL2 TTF when finished.

Here's an example code snippet that displays the text "Hello, World!" on the screen in white color:

#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>

int main(int argc, char** argv) {
    SDL_Init(SDL_INIT_VIDEO);
    TTF_Init();

    SDL_Window* window = SDL_CreateWindow("SDL2 TTF Example", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, 0);
    SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);

    TTF_Font* font = TTF_OpenFont("Arial.ttf", 28);
    SDL_Color color = { 255, 255, 255 };
    SDL_Surface* surface = TTF_RenderText_Solid(font, "Hello, World!", color);
    SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surface);

    SDL_Rect rect = { 100, 100, surface->w, surface->h };
    SDL_RenderCopy(renderer, texture, NULL, &rect);

    SDL_RenderPresent(renderer);
    SDL_Delay(3000);

    SDL_FreeSurface(surface);
    SDL_DestroyTexture(texture);
    TTF_CloseFont(font);
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    TTF_Quit();
    SDL_Quit();

    return 0;
}

Note that this example assumes that the font file "Arial.ttf" can be found in the current working directory.