Ask Your Question
2

How to display text on a window using the SDL2 TTF library?

asked 2022-04-11 11:00:00 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-02-07 06:00:00 +0000

lakamha gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-04-11 11:00:00 +0000

Seen: 16 times

Last updated: Feb 07 '23