C ProgrammingUnit 1310 min read
Graphics Programming in C: Functions, Drawing & Visualization
Unit 13 of C Programming covers graphics programming fundamentals using the graphics.h library, including initialization, drawing primitives (lines, circles, rectangles), color management, and coordinate systems—with real-world applications in visualization tools and interactive apps.
TAKEAWAYS:
- Graphics programming in C uses
graphics.h(BGI library) to draw shapes, lines, and text via functions likeinitgraph(),circle(), andline(). - The coordinate system in graphics starts at
(0,0)(top-left) and increases downward/rightward, unlike math conventions. - Colors are set using
setcolor()(foreground) andsetbkcolor()(background) with predefined constants (e.g.,RED,GREEN). - Drawing functions require pixel coordinates and radii (for circles/ellipses) or endpoints (for lines).
- Real-world use: Apps like eSewa’s transaction confirmations (visual feedback) or NTC’s network topology diagrams rely on similar graphics principles.
- Exam focus: Expect programming questions (drawing shapes) and conceptual questions (e.g.,
initgraph()purpose, coordinate systems).
1. Introduction to Graphics Programming in C
Graphics programming in C allows you to create 2D visualizations using the BGI (Borland Graphics Interface) library (graphics.h). This unit teaches how to:
- Initialize the graphics environment.
- Draw basic shapes (lines, circles, rectangles).
- Manage colors and fill styles.
- Work with coordinate systems.
Why Use Graphics in C?
- Visual feedback: Apps like Khalti’s transaction receipts use simple graphics for confirmation icons.
- Data visualization: NEPSE stock charts (hypothetical C-based tool) could plot trends using lines/circles.
- Games/Simulations: Early games (e.g., Snake clone) used
graphics.hfor rendering.
2. Setting Up the Graphics Environment
Before drawing, you must initialize the graphics mode using initgraph().
Key Functions
| Function | Purpose | Example Usage |
|---|---|---|
initgraph() |
Initializes graphics mode and sets display driver. | initgraph(&gd, &gm, "C:\\TURBOC3\\BGI"); |
closegraph() |
Closes graphics mode and deallocates resources. | closegraph(); |
getmaxx() |
Returns the maximum X-coordinate (width) of the screen. | int width = getmaxx(); |
getmaxy() |
Returns the maximum Y-coordinate (height) of the screen. | int height = getmaxy(); |
Coordinate System in Graphics
- Origin:
(0, 0)is the top-left corner (unlike math, where(0,0)is center). - X-axis: Increases rightward.
- Y-axis: Increases downward.
- Example: To draw a circle centered at
(50, 50)with radius30, usecircle(50, 50, 30).
3. Drawing Basic Shapes
A. Drawing a Line
- Function:
line(int x1, int y1, int x2, int y2) - Example: Draw a line from
(50, 50)to(150, 150).line(50, 50, 150, 150);
B. Drawing a Circle
- Function:
circle(int x, int y, int radius) - Example: Draw a circle at
(100, 100)with radius50.circle(100, 100, 50);
C. Drawing a Rectangle
- Function:
rectangle(int x1, int y1, int x2, int y2) - Example: Draw a rectangle from
(50, 50)to(150, 100).rectangle(50, 50, 150, 100);
D. Drawing an Ellipse
- Function:
ellipse(int x, int y, int start_angle, int end_angle, int x_radius, int y_radius) - Example: Draw an ellipse centered at
(100, 100)with radii60(x) and40(y).ellipse(100, 100, 0, 360, 60, 40);
4. Managing Colors and Fill Styles
A. Setting Colors
| Color Constant | Value | Usage Example |
|---|---|---|
RED |
4 | setcolor(RED); |
GREEN |
2 | setcolor(GREEN); |
BLUE |
1 | setcolor(BLUE); |
WHITE |
15 | setcolor(WHITE); |
BLACK |
0 | setcolor(BLACK); |
B. Setting Background Color
- Function:
setbkcolor(int color) - Example: Set background to green.
setbkcolor(GREEN);
C. Filling Shapes
- Function:
setfillstyle(int pattern, int color)- Patterns:
EMPTY_FILL,SOLID_FILL,LTSLASH_FILL, etc.
- Patterns:
- Example: Fill a circle with a solid blue color.
setfillstyle(SOLID_FILL, BLUE); floodfill(x, y, border_color); // Fills from (x,y) until border_color
5. Real-World Applications
Example 1: eSewa Transaction Confirmation
- Idea Used: Simple graphics for feedback.
- How: After a payment, eSewa shows a green checkmark icon (drawn using
circle()+line()) to confirm success. - Code Snippet:
setcolor(GREEN); circle(100, 100, 20); // Checkmark circle line(80, 100, 100, 120); // Checkmark line
Example 2: NTC Network Topology Visualizer
- Idea Used: Drawing lines/circles for nodes and connections.
- How: A hypothetical C tool could plot network switches as circles and connections as lines to debug routes.
- Code Snippet:
circle(50, 50, 15); // Switch 1 circle(150, 50, 15); // Switch 2 line(65, 50, 135, 50); // Connection
Example 3: Daraz Order Status Animation
- Idea Used: Progressive drawing (e.g., loading bar).
- How: While an order processes, Daraz could show a filling rectangle to indicate progress.
- Code Snippet:
rectangle(50, 50, 200, 70); // Outline setfillstyle(SOLID_FILL, BLUE); bar(50, 50, 100, 70); // Fills 25% (adjust width dynamically)
6. Worked Example: Drawing Concentric Circles
Problem: Draw two concentric circles centered at (50, 50) with radii 75 and 125.
Step-by-Step Code
#include <graphics.h>
#include <stdio.h>
int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "C:\\TURBOC3\\BGI");
// Draw outer circle (radius 125)
setcolor(RED);
circle(50, 50, 125);
// Draw inner circle (radius 75)
setcolor(BLUE);
circle(50, 50, 75);
getch();
closegraph();
return 0;
}
State After Each Step
Output Visualization
7. Worked Example: Drawing a House
Problem: Draw a simple house with a rectangular body, triangular roof, and a door.
Code
#include <graphics.h>
int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "C:\\TURBOC3\\BGI");
// House body (rectangle)
rectangle(100, 100, 200, 200);
// Roof (triangle)
line(100, 100, 150, 50);
line(150, 50, 200, 100);
// Door (rectangle)
rectangle(130, 150, 170, 200);
getch();
closegraph();
return 0;
}
State After Each Step
Output Visualization
8. Common Mistakes and Fixes
| Mistake | Cause | Fix |
|---|---|---|
| No output appears | initgraph() failed |
Check path to BGI files. |
| Shapes drawn at wrong positions | Incorrect coordinates | Verify (x,y) values. |
| Colors not changing | setcolor() not called |
Call setcolor() before drawing. |
| Program crashes | Missing closegraph() |
Always call closegraph() at end. |
9. Exam Tip
- Memorize key functions:
initgraph(),closegraph(),circle(),line(),rectangle().setcolor(),setbkcolor(),setfillstyle().
- Coordinate system:
(0,0)is top-left, not center.- X increases right, Y increases down.
- Programming questions:
- Expect drawing shapes (e.g., concentric circles, house).
- Trace the code step-by-step (e.g., where
circle()is called).
- Real-world tie-ins:
- Relate to eSewa/Khalti icons, NTC network diagrams, or Daraz progress bars.
- Common pitfalls:
- Forgetting
closegraph()→ loss of marks. - Wrong path in
initgraph()→ no output.
- Forgetting
10. Practice Questions
- Write a program to draw a square with side length
100centered at(100, 100). - Draw a star using
line()(hint: connect 5 points). - Modify the house example to include a window (small rectangle).
- Explain how
setfillstyle(SOLID_FILL, RED)works when drawing a circle.
11. Summary Table
| Concept | Function/Example | Key Point |
|---|---|---|
| Initialize Graphics | initgraph(&gd, &gm, "path") |
Must be called first. |
| Draw Line | line(x1,y1,x2,y2) |
Connects two points. |
| Draw Circle | circle(x,y,radius) |
Center (x,y), radius r. |
| Set Color | setcolor(RED) |
Changes pen color. |
| Fill Shape | setfillstyle(SOLID_FILL, BLUE) |
Fills shapes with color/pattern. |
| Coordinate System | (0,0) = top-left |
Opposite of math conventions. |
12. Final Notes
- Always include
closegraph()to avoid memory leaks. - Test with small coordinates first (e.g.,
(50,50)) before scaling up. - Use
getch()to pause the program and see the output.
Visual Recap:
Based on the TU BCA syllabus for C Programming (CACS151), unit 13.
Discussion
Loading…