Fundamental Graphics Functions
On this page (3sections)
Fundamental Graphics Functions
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.
Related Tutorials
2D Scaling Program in C: Understanding Graphics Transformation...
In computer graphics, scaling is a fundamental transformation that alters the size of an object while preserving its shape. It is commonly used to zoom in or ou
Read tutorial2D Rotation Program Using C Programming
In computer graphics, transformations play a crucial role in manipulating objects on the screen. One such fundamental transformation is rotation, which involves
Read tutorial2D Translation Rectangle Program Using C Programming
In computer graphics, translating an object means moving it from one position to another within the coordinate space. In this blog post, we will explore a C pro
Read tutorial