Saturday, November 5, 2011

2D C++ Game: Part 4 - Draw Text Using Fonts

Inorder to use font functions in Allegro we need to include two more additional libraries i.e allegro_font.h and allegro_ttf.h along with allegro.h which is the core library. I have used arial.ttf font file for this program, you can use any other font file of your own choice. Make sure you copy the font file to the project directory or if it is in any other location, then input the proper path of the file while loading the font file in the program.

Objective: Display 'Hello World' on the screen using fonts.
#include <allegro5/allegro.h>
#include <allegro5/allegro_font.h>
#include <allegro5/allegro_ttf.h>

#define SCREEN_W 640
#define SCREEN_H 480
int main()
{
    al_init();
    ALLEGRO_DISPLAY *screen = NULL;
    screen = al_create_display(SCREEN_W, SCREEN_H);

    al_init_font_addon();
    al_init_ttf_addon();

    ALLEGRO_FONT *font = NULL;
    font=al_load_ttf_font("arial.ttf", 15, 0);
    al_draw_text(font, al_map_rgb(255,255,255), SCREEN_W/2, SCREEN_H/2, ALLEGRO_ALIGN_CENTRE, "Hello World");
    al_flip_display();

    al_rest(3.0);
    al_destroy_display(screen);
}
Explanation:
al_init_font_addon();al_init_ttf_addon();
To use these font functions, we will need to initialize the font addon by using al_init_font_addon. Along with that we will need to initialize ttf addon as well because we will be using al_load_ttf_font() function later in the program which needs ttf addon.

▪ ALLEGRO_FONT *font;
We declare a ALLEGRO_FONT structure which will hold our font and intialize it to NULL.

▪ font=al_load_ttf_font("arial.ttf", 15, 0);
Then we need to load the font using al_load_ttf_font(char const *filename, int size, int flags) function which takes three parameters i.e font file path, size of the font to be displayed and flags which you can leave it to 0. This function returns ALLEGRO_FONT structure, which we will use to initialize our pointer we had declared.

▪ al_draw_text(font, al_map_rgb(255,255,255), SCREEN_W/2, SCREEN_H/2, ALLEGRO_ALIGN_CENTRE, "Hello World");
Then we will use al_draw_text(const ALLEGRO_FONT *font, ALLEGRO_COLOR color, float x, float y, int flags, char const *text) function to draw desired text on the back buffer using our specified font. This function takes 6 parameters as follows:
 ALLEGRO_FONT structure which holds our font.
 ALLEGRO_COLOR structure to specify the colour of the text, for which we will use al_map_rgb(r,g,b) as parameter.
 X coordinate of the text to be drawn on the screen.
 Y coordinate of the text to be drawn on the screen.
 The flags parameter can be 0 or one of the following flags:
ALLEGRO_ALIGN_LEFT - Draw the text left-aligned (same as 0).
ALLEGRO_ALIGN_CENTRE - Draw the text centered around the given position.
ALLEGRO_ALIGN_RIGHT - Draw the text right-aligned to the given position.
 Input the text to be drawn on the screen.

Output:

0 comments:

Post a Comment