Sunday, December 6, 2015

HOW TO DISPLAYING TEXT USING SDL2

Hey, coding-ers! wkwk
In the last post, I've already explain about SDL and How to load image and display it in SDL, right? Now, I will give you the another tutorial using SDL2. We will learn about HOW TO DISPLAYING TEXT USING SDL2. YEAY!
Here we go....
When we want to display an image we use SDL_image library. But now we want to display text. We will use SDL_ttf library now! To setting it up is almost same to how we setting up SDL_image.
First, make a new project. Dont forget to write the location of includepath and library in .pro file. And also add -lSDL2_ttf after the location of library.


This is the source code for displaying the text...
#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h> //include the relevant header file//

int main(int argc, char ** argv)
{
    bool quit = false;
    SDL_Event event;

    SDL_Init(SDL_INIT_VIDEO);
    TTF_Init(); //initialise the SDL_ttf library//

    SDL_Window * window = SDL_CreateWindow("SDL_ttf in SDL2",
        SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640,
        480, 0);
    SDL_Renderer * renderer = SDL_CreateRenderer(window, -1, 0);
    TTF_Font * font = TTF_OpenFont("calibri.ttf", 25);
    //load a font into memory// 
    SDL_Color color = { 255, 255, 255 };
    SDL_Surface * surface = TTF_RenderText_Solid(font,
     "Welcome to My SDL", color);//the text//
    SDL_Texture * texture = SDL_CreateTextureFromSurface(renderer, surface);

    while (!quit)
    {
        SDL_WaitEvent(&event);

        switch (event.type)
        {
            case SDL_QUIT:
                quit = true;
                break;
        }
    }

    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    SDL_DestroyTexture(texture);
    SDL_FreeSurface(surface);
    SDL_RenderCopy(renderer, texture, NULL, NULL);
    SDL_RenderPresent(renderer);

    TTF_Quit();//shut down the SDL_ttf//
    SDL_Quit();

    return 0;
}

And when we compile+run this project, it will show a window with text that we've made inside the window. It is cool, isn't it?~
It's almost the same with displaying the image right??? I believe that you can try it by yourself at home wkwkwk
Okay, it's your turn guys! Have a great time with coding luv!

No comments:

Post a Comment