C ProgrammingUnit 119 min read
C Graphics: Pixels, Coordinates, and Drawing Basics
Unit 11 of C Programming introduces fundamental graphics programming in C, covering pixel manipulation, coordinate systems, and basic drawing techniques using libraries like graphics.h. This note explains how to plot points, draw lines, shapes, and text, with real-world applications in visualization tools and games.
TAKEAWAYS:
- Understand the pixel grid and coordinate system (screen vs. logical) for graphics programming.
- Learn to use
graphics.hfunctions likeinitgraph(),circle(), andline()for drawing. - Master color handling (RGB, predefined colors) and text output (
outtextxy()). - Explore real-world applications of C graphics in apps like eSewa’s transaction visualizations and Pathao’s route maps.
- Trace step-by-step execution of drawing algorithms (e.g., filling a circle) to debug errors.
- Compare hardware vs. software rendering and their trade-offs in performance.
1. Introduction to Computer Graphics in C
Computer graphics in C involves creating visual elements (points, lines, shapes) on a screen using libraries like graphics.h. This unit focuses on 2D graphics, where images are constructed using pixels (picture elements) arranged in a grid.
1.1 Pixel and Coordinate Systems
- Pixel: The smallest addressable element on a screen (e.g., a 1920×1080 display has 1920×1080 pixels).
- Coordinate System:
- Screen Coordinates: Origin (0,0) is the top-left corner of the screen.
- Logical Coordinates: Origin can be customized (e.g., (0,0) at the center).
- Example: To draw a point at the center of a 640×480 screen:
Trace:#include <graphics.h> int main() { int gd = DETECT, gm; initgraph(&gd, &gm, NULL); putpixel(320, 240, WHITE); // Center point getch(); closegraph(); return 0; }Step Action Screen State 1 initgraph()Graphics mode initialized 2 putpixel(320, 240, WHITE)White pixel at (320, 240) appears
1.2 Graphics Modes and Initialization
graphics.hsupports multiple modes (e.g.,VGAHIfor 640×480, 16 colors).- Key Functions:
initgraph(&gd, &gm, "path"): Initializes graphics mode.closegraph(): Closes graphics mode.getgraphmode(): Returns current mode.getmaxx()/getmaxy(): Returns screen dimensions.
2. Drawing Basic Shapes
2.1 Points and Lines
putpixel(x, y, color): Draws a pixel at(x, y).line(x1, y1, x2, y2): Draws a line from(x1, y1)to(x2, y2).- Example: Draw a triangle with vertices at (100,100), (200,200), (150,250).
Visual Trace:line(100, 100, 200, 200); line(200, 200, 150, 250); line(150, 250, 100, 100);
2.2 Circles, Rectangles, and Filled Shapes
circle(x, y, radius): Draws a circle centered at(x, y).rectangle(left, top, right, bottom): Draws a rectangle.floodfill(x, y, border_color): Fills an area starting from(x, y).- Example: Draw a filled red circle with a blue border.
State After Each Step:circle(300, 200, 50); // Draw circle setfillstyle(SOLID_FILL, RED); floodfill(300, 200, BLUE); // Fill with red
3. Text and Color Handling
3.1 Outputting Text
outtextxy(x, y, "text"): Displays text at(x, y).- Example: Display "Hello, TU!" at (100, 100).
outtextxy(100, 100, "Hello, TU!");
3.2 Color Management
- Predefined Colors:
BLACK,BLUE,GREEN,RED,WHITE, etc. - RGB Colors: Use
setcolor(RGB(red, green, blue)). - Example: Draw a gradient line from red to blue.
Visual Trace:for (int i = 0; i <= 300; i++) { setcolor(RGB(i, 0, 300 - i)); putpixel(i, 200, getmaxcolor()); }
4. Real-World Applications
4.1 eSewa: Transaction Visualization
- Use Case: eSewa displays transaction flows as animated arrows between accounts.
- How C Graphics Helps:
- Draws lines to represent money transfers.
- Uses
delay()to animate steps (e.g., "Processing..."). - Example: Simulate a transfer from User A to User B.
line(100, 100, 300, 100); // Transfer arrow outtextxy(200, 90, "Rs. 500"); delay(1000); // Simulate delay
4.2 Pathao: Route Mapping
- Use Case: Pathao shows driver routes on a map using C graphics.
- How C Graphics Helps:
- Plots start/end points as circles.
- Draws polylines for the route.
- Example: Plot a route from Kathmandu to Lalitpur.
circle(100, 100, 3); // Start point circle(400, 100, 3); // End point line(100, 100, 200, 150); line(200, 150, 400, 100);
4.3 NTC Traffic Light Simulation
- Use Case: Simulate traffic light timings for Kathmandu’s busy intersections.
- How C Graphics Helps:
- Draws red/green/yellow circles and switches colors using
delay(). - Example:
setcolor(RED); circle(200, 200, 30); delay(5000); // Red for 5 sec setcolor(GREEN); circle(200, 200, 30);
- Draws red/green/yellow circles and switches colors using
5. Advanced Topics (Optional)
5.1 Mouse and Keyboard Input
getmouseclick(): Detects mouse clicks.getch(): Captures keyboard input.- Example: Draw a shape when a key is pressed.
if (getch() == 'c') { circle(300, 200, 50); }
5.2 Animation Basics
delay(milliseconds): Pauses execution.- Example: Animate a bouncing ball.
int x = 100, y = 100, dx = 2, dy = 2; while (y < 400) { putpixel(x, y, WHITE); delay(50); x += dx; y += dy; }
6. Comparison: Hardware vs. Software Rendering
| Feature | Hardware Rendering | Software Rendering |
|---|---|---|
| Speed | Faster (GPU-accelerated) | Slower (CPU-based) |
| Quality | Higher (anti-aliasing, shading) | Lower (basic shapes) |
| Complexity | Requires GPU support | Works on any system |
| Use Case | Games, 3D apps | Simple 2D graphics, simulations |
7. Common Errors and Debugging
Graphics error: initgraph- Cause: Missing
graphics.hor incorrect driver path. - Fix: Use
initgraph(&gd, &gm, NULL)or installgraphics.hdrivers.
- Cause: Missing
Shapes Not Appearing
- Cause: Coordinates out of bounds (
x > getmaxx()). - Fix: Check
getmaxx()andgetmaxy()before drawing.
- Cause: Coordinates out of bounds (
Floodfill Not Working
- Cause: Border color mismatch.
- Fix: Ensure
floodfill(x, y, border_color)uses the correct color.
Exam Tip
- Understand Coordinates: Always verify
(x, y)ranges usinggetmaxx()/getmaxy(). - Step-by-Step Drawing: For questions like "Draw a house," break it into:
- Rectangle (walls)
- Triangle (roof)
- Circle (door)
- Color Handling: Remember
setcolor()must precedeputpixel()/line(). - Animation: Use
delay()to simulate real-time changes (e.g., moving objects). - Real-World Scenarios: Expect questions on visualizing data (e.g., "Plot a bar graph for TU exam scores").
Practice Question: Write a C program to draw a smiley face using:
- A circle for the face.
- Two smaller circles for eyes.
- A line for the mouth. Trace the state after each drawing step.
Based on the TU BIM syllabus for C Programming (IT232), unit 11.
Discussion
Loading…