5.2.2 Drawing Lines and Rectangles
The next step up from the lowly pixel is the line, and Allegro provides several line-drawing functions. To keep things as efficient as possible, Allegro divides line drawing among three functions—one for horizontal lines, one for vertical lines, and a third for every other type of line. Drawing horizontal and vertical lines can be an extremely optimized process using a simple high-speed memory copy, but non-aligned lines must be drawn using an algorithm to fill in the pixels between two points specified for the line (see Figure 3.3).
5.2.2.1 Horizontal Lines
The horizontal line-drawing function is called hline:
void hline(BITMAP *bmp, int x1, int y, int x2, int color)
Because this is your first function for drawing lines, allow me to elaborate. The
first parameter, BITMAP *bmp, is the destination bitmap for the line, which can be
‘‘screen’’ if you want to draw directly to the screen. The next three parameters,
int x1, int y, and int x2, specify the two points on the single horizontal Y-axis
where the line should be drawn. The HLines program (shown in Figure 3.4)
demonstrates how to use this function.
Figure 3.4
The HLines program draws horizontal lines.
#include
#include "allegro.h"
int main(void)
{
int x,y,x1,y1,x2,y2;
int red,green,blue,color;
//initialize Allegro
allegro init();
//initialize the keyboard
install keyboard();
110 Chapter 3 n 2D Vector Graphics Programming
Figure 3.9
A line is comprised of pixels filled in between point A and point B.
//initialize random seed
srand(time(NULL));
//initialize video mode to 640x480
int ret = set gfx mode(GFX AUTODETECT WINDOWED, 640, 480, 0, 0);
if (ret != 0) {
allegro message(allegro error);
return 1;
}
//display screen resolution
textprintf ex(screen, font, 0, 0, 15, -1,
"HLines Program - %dx%d - Press ESC to quit",
SCREEN W, SCREEN H);
//wait for keypress
while(!key[KEY ESC])
{
//set a random location
x1 = 10 + rand() % (SCREEN W-20);
y = 10 + rand() % (SCREEN H-20);
x2 = 10 + rand() % (SCREEN W-20);
Drawing Graphics Primitives 111
Figure 3.10
The HLines program draws horizontal lines.
//set a random color
red = rand() % 255;
green = rand() % 255;
blue = rand() % 255;
color = makecol(red,green,blue);
//draw the horizontal line
hline(screen, x1,y,x2,color);
}
//end program
allegro exit();
return 0;
}
END OF MAIN()
You have probably noticed that the HLines program is very similar to the Pixels
program, with only a few lines that differ inside the while loop. I’ll just show the
differences from this point forward, rather than listing the entire source code for
each program, because in most cases you simply need to replace a few lines inside
main. It is pretty obvious that just a few lines inside the while loop need to be
changed. The entire programs are available on the CD-ROM in complete form,
but I will provide only partial listings where such changes are needed to
demonstrate each of these graphics primitives.
Chia sẻ với bạn bè của bạn: |