03. Basics of graphics - "graphics.h" library, C++
Graphics Console
When you write simple programs and run it, the output is shown in a text based console like Command Prompt and Terminal. The problem with these console is that, it is designed to represent text only. So, you can't draw any shapes in it. Somehow, even if you try to draw any shapes like circle using characters, it will not be accurate. So, we need a window in which we can draw any kind of shapes easily and here comes the concept of console in graphics mode.
This graphics window is basically a lot of pixels arranged in rows and columns. Pixel is nothing but the smallest point in raster image. Even your monitor and phone display is made of smallest addressable element which is known as pixel (or Picture Element). These pixels have a special property that it holds color data and when you see all these pixels together, it appears to be an image of something and that is how it works.
Creating Graphics Window
So, now we know why do we need to create graphics window (or graphics console). But now the question is How to create a graphics window? So now we will create new program in CodeBlocks in C++ language which will create a graphics window. We will use "graphics.h" library for it. To setup graphics.h in CodeBlocks, read (How to setup "graphics.h" in CodeBlocks?).
So, lets create a new C++ program which will open console in graphics mode. Open CodeBlocks, Create a new project and write the following code.
#include <graphics.h>
int main()
{
int gd=DETECT, gm;
initgraph(&gd, &gm, (char*)"C:\\TC\\BGI") ;
getch();
closegraph();
return 0;
}
Code Explanation
As we are using "graphics.h", So in the
first line I have included
In the next line, I have called
NOTE: (i) In C++, anything that you write in double quotes "" is
treated as
(ii) The path provided is used in Turbo C++ IDE and it can be different in your case depending upon how Turbo C++ is installed in your computer and in CodeBlocks, it is not mandatory to write the whole path. If you pass an empty string, even then your program will work.
In the next line, I have called the
Finally, as the main function return an
integer, so I have written
One more thing you can notice in the program
that I have used
Now build and run the program. You can use F9 key also.
Output
So, in the above output, you can see a graphics window is created. The top-left corner is the origin i.e. here, the value of x and y coordinates is zero. The value of x increases as you go from left to right and the value of y increases from top to bottom of this window. In other words, you can say it is a two dimensional coordinate system with y-axis inverted and the origin at top-left corner of this window.
0 Comments
If you have any doubts, Please let me know.