C ProgrammingUnit 1111 min read
C Graphics: Drawing Shapes, Coordinates & Pixel Manipulation
Unit 11 of C Programming introduces graphics programming in C using libraries like graphics.h, covering coordinate systems, drawing shapes (lines, circles, rectangles), and basic animation principles. This note explains syntax, algorithms, and real-world applications with visual traces of operations.
TAKEAWAYS:
- Understand the graphical coordinate system (origin, axes, pixel units) and how it maps to screen output.
- Master drawing primitives (
line(),circle(),rectangle(),arc()) and their parameters. - Learn color handling (RGB values,
setcolor(),setbkcolor()) and filling shapes (setfillstyle()). - Trace animation loops using
delay()andcleardevice()for simple motion effects. - Apply graphics to real-world scenarios like UI elements, data visualization, or game development.
- Compare hardware vs. software rendering and limitations of
graphics.hin modern systems.
1. Graphics Programming Basics in C
C graphics are built on pixel manipulation and device-independent coordinates. The graphics.h library (part of Turbo C) provides functions to draw shapes, set colors, and manage the display.
1.1 Coordinate System in C Graphics
- The origin (0,0) is the top-left corner of the screen (unlike math, where it’s bottom-left).
- X-axis: Moves right; Y-axis: Moves down.
- Resolution: Typically
640x480(default in Turbo C), but can be changed withinitgraph(). - Pixel: Smallest addressable unit on the screen (e.g.,
(100, 200)is 100 pixels right, 200 pixels down).
Example: Drawing a point at (100, 150):
#include <graphics.h>
int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm);
putpixel(100, 150, WHITE); // Draws a white pixel at (100,150)
getch();
closegraph();
return 0;
}
2. Drawing Shapes
2.1 Lines (line())
- Syntax:
line(int x1, int y1, int x2, int y2) - Parameters:
(x1,y1): Start point.(x2,y2): End point.
- Example: Draw a diagonal line from
(50,50)to(200,200).line(50, 50, 200, 200);
2.2 Circles (circle())
- Syntax:
circle(int x, int y, int radius) - Parameters:
(x,y): Center of the circle.radius: Distance from center to edge.
- Example: Draw a circle centered at
(200,200)with radius50.circle(200, 200, 50);
2.3 Rectangles (rectangle())
- Syntax:
rectangle(int x1, int y1, int x2, int y2) - Parameters:
(x1,y1): Top-left corner.(x2,y2): Bottom-right corner.
- Example: Draw a rectangle from
(100,100)to(300,200).rectangle(100, 100, 300, 200);
2.4 Filling Shapes (setfillstyle())
- Syntax:
setfillstyle(int pattern, int color) - Patterns:
EMPTY_FILL,SOLID_FILL,LINE_FILL, etc. - Example: Fill a circle with blue cross-hatch pattern.
setfillstyle(HATCH_FILL, BLUE); floodfill(200, 200, WHITE); // Fills from (200,200) outward
Visual Trace of circle():
(150,200) •-------------------• (250,200)
| |
| |
| • |
| |
(200,150) •-------------------• (200,250)
3. Colors in C Graphics
- Predefined Colors:
BLACK,BLUE,GREEN,CYAN,RED,MAGENTA,YELLOW,WHITE. - RGB Colors: Use
setrgbpalette()(advanced). - Example: Set background to red and text to green.
setbkcolor(RED); setcolor(GREEN); outtextxy(100, 100, "Hello!");
4. Animation in C Graphics
Animation is achieved by clearing the screen and redrawing shapes with slight changes.
- Key Functions:
delay(int milliseconds): Pauses execution.cleardevice(): Erases the screen.
- Example: Moving a circle from left to right.
for (int x = 0; x < 640; x++) { cleardevice(); circle(x, 200, 20); delay(50); }
flowchart TD
A["Start"] --> B["cleardevice()"]
B --> C["Draw shape at (x,y)"]
C --> D["delay(50)"]
D --> E["Increment x"]
E -->|"x < 640?"| C
C --> F["End"]Animation loop pseudocode (circle moving right)Visual Trace of Animation Loop:
5. Real-World Applications
In the Real World
eSewa App (Nepal):
- Uses pixel-based graphics for UI buttons (e.g., "Pay Now" rectangles) and color coding (green for success, red for errors).
- Example: The confirmation screen after a payment uses
rectangle()-like borders andcircle()for checkmarks.
Pathao Driver App:
- Dynamic maps rely on
line()to draw roads andcircle()for driver/passenger markers. - Real-time updates use
cleardevice()-like refreshes to redraw routes.
- Dynamic maps rely on
Nepal Stock Exchange (NEPSE) Dashboard:
- Stock price graphs are plotted using
line()to connect data points (e.g.,(x=day, y=price)). - Example: A rising line from
(1,100)to(30,150)shows a price increase over 30 days.
- Stock price graphs are plotted using
WhatsApp Stickers:
- Custom stickers are created using
circle(),rectangle(), andsetfillstyle()for patterns. - Animation (e.g., bouncing balls) uses the same
delay()+cleardevice()loop.
- Custom stickers are created using
6. Worked Example: Drawing a House
Task: Draw a house with a rectangular body, triangular roof, and a circular window. Solution:
#include <graphics.h>
int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm);
```figure
{"type":"graph","fns":[{"expr":"x","label":"Roof (triangle)","color":"black","dash":false},{"expr":"200","label":"House base (y=200)","color":"black","dash":true}],"x":[0,400],"y":[0,350],"points":[{"x":100,"y":200,"label":"Base-left (100,200)","color":"black"},{"x":300,"y":200,"label":"Base-right (300,200)","color":"black"},{"x":200,"y":100,"label":"Roof peak (200,100)","color":"black"},{"x":150,"y":250,"label":"Window (150,250)","color":"red","size":10}],"caption":"House structure coordinates (rectangle + triangle + circle)"}
// Draw house body (rectangle)
rectangle(100, 200, 300, 350);
// Draw roof (triangle)
line(100, 200, 200, 100);
line(200, 100, 300, 200);
// Draw window (circle)
circle(150, 250, 20);
// Fill window with yellow
setfillstyle(SOLID_FILL, YELLOW);
floodfill(150, 250, WHITE);
getch();
closegraph();
return 0;
}
**State After Each Step**:
+---------------------+
| |
| |
+---------------------+
- Roof: Lines from (100,200) to (200,100) to (300,200)
/\ / \ +----+ - Window: Circle at (150,250), radius 20
+---------------------+
| •••••• |
| • |
| • |
+---------------------+
7. Limitations of graphics.h
| Advantage | Disadvantage |
|---|---|
| Simple to learn | Only works in Turbo C/Borland C++ |
| Fast for basic shapes | No support for modern APIs (OpenGL, SDL) |
| Easy animation loops | Limited color depth (256 colors max) |
| Device-independent | Outdated; not used in professional apps |
Modern Alternatives:
- OpenGL: For 3D graphics (used in games like Call of Duty).
- SDL: Cross-platform library (used in Pathao for animations).
- HTML5 Canvas: Web-based graphics (used in eSewa web dashboards).
8. Exam Tip
Syntax is Key:
- Memorize
initgraph(),circle(),rectangle(),setfillstyle(), andfloodfill(). - Example question: "Write code to draw a rectangle with a red border and blue fill."
Answer:
setfillstyle(SOLID_FILL, BLUE); bar(100, 100, 300, 200); // bar() fills and draws setcolor(RED); rectangle(100, 100, 300, 200);
- Memorize
Coordinate Confusion:
- Always assume
(0,0)is top-left unless specified otherwise. - Example: "Draw a line from (50,50) to (50,200)." This is a vertical line (not horizontal).
- Always assume
Animation Logic:
- Exams may ask for a loop to move an object. Always include:
cleardevice()to erase.delay()for timing.- Increment/decrement coordinates.
- Example: "Write code to move a circle rightward."
for (int x = 0; x < 640; x++) { cleardevice(); circle(x, 200, 10); delay(100); }
- Exams may ask for a loop to move an object. Always include:
Visual Traces:
- If asked to "show the state after each step", draw the before/after of operations like:
- Inserting a node in a BST (here: drawing a shape).
- Filling a rectangle (show outline vs. filled).
- If asked to "show the state after each step", draw the before/after of operations like:
Common Pitfalls:
- Forgetting
closegraph()→ Program may crash. - Using
getch()withoutinitgraph()→ Error. - Mixing
line()andcircle()coordinates → Shapes misaligned.
- Forgetting
Practice Question:
"Write a program to draw a smiley face using circle(), line(), and setfillstyle(). The face should have a yellow fill, black eyes, and a red smile."
Hint: Use arc() for the smile (or two line() segments).
In the real world
- eSewa App: Uses
rectangle()for UI buttons (e.g., 'Pay Now' green rectangles) andcircle()for loading spinners during payment processing. The app’s confirmation screen after a transaction usessetfillstyle(SOLID_FILL, GREEN)for success messages. - Pathao Driver App: Dynamically redraws routes using
line()for roads andcircle()for driver/passenger markers. The app clears and redraws the map (cleardevice()) every time the user’s location updates. - Nepal Stock Exchange (NEPSE) Dashboard: Plots stock price trends using
line()to connect(day, price)data points (e.g.,(1,100)to(30,150)for a 30-day price increase). The dashboard refreshes graphs using animation loops (delay()+cleardevice()).
Based on the TU BITM syllabus for C Programming (IT232), unit 11.
Discussion
Loading…