How to Use Allegro to Make Graphics in C

Allegro is a game programming library for the C language, allowing you to receive user input, play sounds and display graphics. The library is designed to be easy to understand, using powerful functions with intuitive names for concise, readable code. A simple graphics program that displays an image can be written very quickly, requiring only a few lines of C code to load the image into memory and draw it to the screen.

Instructions

    • 1

      Download and install the Allegro libraries for use with your C compiler. Begin a new C code file, whether in your IDE or using a simple text editor such as gedit or Notepad.

    • 2

      Include the Allegro header files at the beginning of your code to allow you to use both the core and graphics functions provided by the library. The first lines should look like this:

      #include <allegro5/allegro.h>

      #include <allegro5/allegro_image.h>

    • 3

      Begin the main() function and call the functions to initialize Allegro, allowing you to display graphics. This should look like the following:

      int main(int argc, char *argv[])

      {

      al_init();

      al_init_image_addon();

    • 4

      Create a display upon which to draw graphics, using the function arguments to set the screen resolution to 640 by 480. Create a bitmap image in memory and give it the data found in the file "Image.png" stored on your hard drive. This will look like the following:

      ALLEGRO_DISPLAY *display = al_create_display(640, 480);

      ALLEGRO_BITMAP *bmp = al_load_bitmap("Image.png");

    • 5

      Set the color of the display to black and draw your image upon it at an offset of 50 pixels both horizontally and vertically. Allegro uses two displays, one for drawing and one for printing to the screen. Flip them to see your image and wait 10 seconds before closing the program. The functions to do the above look like this:

      al_clear_to_color(al_map_rgb(0,0,0));

      al_draw_bitmap(bmp, 50, 50, 0);

      al_flip_display();

      al_rest(10.0);

    • 6

      Free the memory used by the bitmap and the display to prevent wasted resources. The final lines of your code should look like this:

      al_destroy_bitmap(bmp);

      al_destroy_display(display);

      return 0;

      }

    • 7

      Compile your code. Create a PNG image using your graphics program of choice and save it as "Image.png" in the same directory as your executable program. Run your program to see the graphics functions at work.

Related Searches:

References

Comments

Related Ads

Featured