You are here

C graphics tutorial

This tutorial is for all those who wish to learn C graphics programming, no knowledge of graphics concepts is required. C Graphics programming is very easy and interesting. You can use graphics programming for developing your games, in making projects, for animation etc. It's not like traditional C programming in which you have to apply complex logic in your program and then you end up with a lot of errors and warnings in your program.

In C graphics programming you have to use standard library functions (don't worry if you don't know functions ) to get your task done. Just you pass arguments to the functions and it's done. On this website you will find almost all functions with detailed explanation and a sample program showing the usage of these functions. To make things easy you are provided with executable files which you can download and execute. Firstly you should know the function initgraph which is used to initialize the graphics mode . To initialize graphics mode we use initgraph function in our program. initgraph function is present in "graphics.h" header file, so your every graphics program should include "graphics.h" header file.

We will discuss initgraph with the help of the following sample program:

Sample graphics code

#include<graphics.h>
#include<conio.h>

int main()
{
   int gd = DETECT, gm;

   initgraph(&gd, &gm, "C:\\TC\\BGI");
       
   getch();
   closegraph();
   return 0;
}

Let me tell you what the output of this program is, this program initializes graphics mode and then closes it after a key is pressed. To begin with we have declared two variables of int type gd and gm for graphics driver and graphics mode respectively, you can choose any other variable name as well. DETECT is a macro defined in "graphics.h" header file, then we have passed three arguments to initgraph function first is the address of gd, second is the address of gm and third is the path where your BGI files are present (you have to adjust this accordingly where you Turbo C compiler is installed). Initgraph function automatically decides an appropriate graphics driver and mode such that maximum screen resolution is set, getch helps us to wait until a key is pressed, closegraph function closes the graphics mode, and finally return statement returns a value 0 to main indicating successful execution of the program. After you have understood initgraph function then you can use functions to draw shapes such as circle, line , rectangle, etc., then you can learn how to change colors and fonts using suitable functions, then you can go for functions such as getimage, putimage, etc., for doing animation.

C graphics programs

These codes show how to use functions of graphics library and simple applications to learn programming. For more advanced applications you can use OpenGL which offers API for 2D and 3D graphics. Many games and application have been developed using it and there are many resources available on the web.