Fundamental Graphics Functions
On this page (4sections)
Graphics programming in C allows you to create visual elements and interactive designs using the fundamental graphics functions provided by the graphics.h library. In this tutorial, we will explore the basic concepts of graphics programming in C and learn how to create simple shapes like circles, lines, and rectangles.
Complete Example Program
The program below initializes the graphics environment, displays a menu, and draws the selected shape using the corresponding graphics function.
#include <stdio.h>
#include <conio.h>
#include <graphics.h>
int main()
{
int gd = DETECT, gm, ch;
initgraph(&gd, &gm, "");
do {
cleardevice();
outtextxy(10, 10, "FUNDAMENTALS");
outtextxy(10, 30, "1. Circle");
outtextxy(10, 45, "2. Line");
outtextxy(10, 60, "3. Rectangle");
outtextxy(10, 75, "4. Exit");
outtextxy(10, 100, "Enter your choice: ");
scanf("%d", &ch);
cleardevice();
switch (ch) {
case 1:
circle(200, 200, 80);
break;
case 2:
line(100, 100, 400, 300);
break;
case 3:
rectangle(150, 150, 350, 250);
break;
}
getch();
} while (ch <= 3);
closegraph();
return 0;
}
Explanation
initgraph()initializes the graphics driver and mode. Parameters:&gd(driver),&gm(mode), and an optional BGI driver path string.cleardevice()clears the graphics window before each menu redraw.outtextxy()displays text at the given coordinates.scanf()reads the user’s menu choice intoch.- The
switchstatement calls the appropriate shape-drawing function for options 1–3. getch()waits for a key press before returning to the menu.closegraph()releases graphics resources when the program exits.
Drawing Shapes
The three shape functions used in the program above are:
Circle — center (x, y) and radius:
circle(x, y, radius);
Line — endpoints (x1, y1) and (x2, y2):
line(x1, y1, x2, y2);
Rectangle — top-left (left, top) and bottom-right (right, bottom):
rectangle(left, top, right, bottom);
In this tutorial, we learned the fundamentals of graphics programming in C: setting up the graphics environment, displaying a menu, and drawing circles, lines, and rectangles. Remember to include the necessary header files and link the graphics library during compilation to successfully run graphics programs in C.
Frequently Asked Questions
What are the fundamental graphics functions in C?
What does initgraph do?
How do I end graphics mode?
Related Tutorials
DDA Line Drawing Algorithm Using C Programming
More in Computer Graphics Programs Using C Programming.
Read tutorialLine Clipping Program Using C Programming
More in Computer Graphics Programs Using C Programming.
Read tutorial3D Rotation Program Using C Programming
More in Computer Graphics Programs Using C Programming.
Read tutorial