TechBytes‎ > ‎

Turbo C graphics Programming

Turbo C graphics Programming
Turbo C has a good collection of graphics libraries. If you know the basics of C, you can easily learn graphics programming. To start programming, let us write a small program that displays a circle on the screen.

/* simple.c
example 1.0

void main()
int gd=DETECT, gm;

initgraph(&gd, &gm, "c:\\turboc3\\bgi " );


To run this program, you need graphics.h header file, graphics.lib library file and Graphics driver (BGI file) in the program folder. These files are part of Turbo C package. In all our programs we used 640x480 VGA monitor. So all the programs are according to that specification. You need to make necessary changes to your programs according to your screen resolution. For VGA monitor, graphics driver used is EGAVGA.BGI. Here, initgraph() function initializes the graphics mode and clears the screen. We will study the difference between text mode and graphics mode in detail latter.

InitGraph: Initializes the graphics system.

void far initgraph(int far *graphdriver, int far *graphmode, char far *pathtodriver);

Remarks: To start the graphics system, you must first call initgraph.


initgraph also resets all graphics settings (color, palette, current position, viewport, etc.) to their defaults, then resets graphresult to 0.


*graphdriver: Integer that specifies the graphics driver to be used. You can give graphdriver a value using a constant of the graphics drivers enumeration type.

*graphmode : Integer that specifies the initial graphics mode (unless *graphdriver = DETECT). If *graphdriver = DETECT, initgraph sets *graphmode to the highest resolution available for the detected driver. You can give *graphmode a value using a constant of the graphics_modes enumeration type. pathtodriver : Specifies the directory path where initgraph looks for graphics drivers (*.BGI) first. If they're not there, initgraph looks in the current directory. If pathtodriver is null, the driver files must be in the current directory. This is also the path settextstyle searches for the stroked character font files (*.CHR).

closegraph() function switches back the screen from graphcs mode to text mode. It clears the screen also. A graphics program should have a closegraph function at the end of graphics. Otherwise DOS screen will not go to text mode after running the program. Here, closegraph() is called after getch() since screen should not clear until user hits a key.

If you have the BGI file in the same folder of your program, you can just leave it as "" only. you need not mention *graphmode if you give *graphdriver as DETECT.
In graphics mode, all the screen co-ordinates are mentioned in terms of pixels. Number of pixels in the screen decides resolution of the screen. In the example 1.0, circle is drawn with x-coordinate of the center 200, y-coordinate 100 and radius 150 pixels. All the coordinates are mentioned with respect to top-left corner of the screen.