C Graphics Programming
C Graphics Programming
The first step in any graphics program is to include graphics.h header file. The graphics.h header
file provides access to a simple graphics library that makes it possible to draw lines, rectangles,
ovals, arcs, polygons, images, and strings on a graphical window.
The second step is initialize the graphics drivers on the computer using initgraph method
of graphics.h library.
void initgraph(int *graphicsDriver, int *graphicsMode, char *driverDirectoryPath);
It initializes the graphics system by loading the passed graphics driver then changing the system
into graphics mode. It also resets or initializes all graphics settings like color, palette, current
position etc, to their default values. Below is the description of input parameters of initgraph
function.
BLACK 0
BLUE 1
GREEN 2
CYAN 3
RED 4
MAGENTA 5
BROWN 6
LIGHTGRAY 7
DARKGRAY 8
LIGHTBLUE 9
LIGHTGREEN 10
LIGHTCYAN 11
COLOR MACRO INTEGER VALUE
LIGHTRED 12
LIGHTMAGENTA 13
YELLOW 14
WHITE 15
At the end of our graphics program, we have to unloads the graphics drivers and sets the screen
back to text mode by calling closegraph function. Here is our first C Graphics program to draw a
straight line on screen.
In this program initgraph function auto detects an appropriate graphics driver and sets graphics
mode maximum possible screen resolution. Then line function draws a straight line from
coordinate (100, 100) to (200, 200). Then we added a call to getch function to avoid instant
termination of program as it waits for user to press any key. At last, we unloads the graphics
drivers and sets the screen back to text mode by calling closegraph function.
void main()
{
//Initialize the variables for the graphics driver and mode
int gd = DETECT, gm;
clrscr();
initgraph(&gd, &gm, "C:\\TURBOC3\\BGI");
//Draw an object. For this example,drawing a rectangle using the rectangle function
rectangle(50,50,100,100);
getch();