Sunday, November 6, 2011

2D C++ Game: Part 5 - Drawing Graphics From Image File

In this part, we will be displaying this image on the screen using allegro_image functions/routines.
house.png
Objective: Load and display image file.
#include <allegro5/allegro.h>
#include <allegro5/allegro_image.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_image_addon();
    ALLEGRO_BITMAP *image= NULL;
    image = al_load_bitmap("house.png");
    al_draw_bitmap(image, SCREEN_W/2, SCREEN_H/2, 0);
    al_flip_display();

    al_rest(5.0);
    al_destroy_display(screen);
    return 0;
}

Explanation:
▪ al_init_image_addon();
Before we start, we need to initialize the image addon first before using any other image related funcitons or routines.

▪ ALLEGRO_BITMAP *image = NULL;
Then we create a pointer 'image' to ALLEGRO_BITMAP structure which will hold our image.

▪ image = al_load_bitmap("house.png");
Then we use al_load_bitmap(const char *filename) function to load the image from a specified path to our ALEGRO_BITMAP structure we created.

▪ al_draw_bitmap(image, SCREEN_W/2, SCREEN_H/2, 0);
Then we draw the image on to the back buffer using al_draw_bitmap(ALLEGRO_BITMAP *bitmap, float dx, float dy, int flags) routine which takes 3 parameters as follows:
 ALLEGRO_BITMAP structure which holds our image.
 X coordinate of the image to be drawn on the screen.
 Y coordinate of the image to be drawn on the screen.
 The flags parameter can be 0 or one of the following flags:
ALLEGRO_FLIP_HORIZONTAL - flip the bitmap about the y-axis.
ALLEGRO_FLIP_VERTICAL - flip the bitmap about the x-axis.

The picture below explains, how the image is displayed on the screen as per our specified parameters.


0 comments:

Post a Comment