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.h functions like initgraph(), circle(), and line() 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:
      #include <graphics.h>
      int main() {
          int gd = DETECT, gm;
          initgraph(&gd, &gm, NULL);
          putpixel(320, 240, WHITE); // Center point
          getch();
          closegraph();
          return 0;
      }
      
      Trace:
      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.h supports multiple modes (e.g., VGAHI for 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).
    line(100, 100, 200, 200);
    line(200, 200, 150, 250);
    line(150, 250, 100, 100);
    
    Visual Trace:
-5-4-3-2-11234550100150200250xyy = xA(100,100)B(200,200)C(150,250)
Triangle formed by connecting three points using line() function (coordinates in pixels)

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.
    circle(300, 200, 50);       // Draw circle
    setfillstyle(SOLID_FILL, RED);
    floodfill(300, 200, BLUE);  // Fill with red
    
    State After Each Step:
-5-4-3-2-112345199.8199.85199.9199.95200200.05200.1200.15200.2yCenter (300,200)
Step-by-step: (1) Draw circle, (2) Set fill style, (3) Flood fill with red (blue border remains)

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.
    for (int i = 0; i <= 300; i++) {
        setcolor(RGB(i, 0, 300 - i));
        putpixel(i, 200, getmaxcolor());
    }
    
    Visual Trace:
50100150200250300150160170180190200210220230240250yi=0, RGB(0,0,300)i=100, RGB(100,0,200)i=300, RGB(300,0,0)
Gradient line created by putpixel() with varying RGB values (i increases from left to right)

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);
      

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

  1. Graphics error: initgraph

    • Cause: Missing graphics.h or incorrect driver path.
    • Fix: Use initgraph(&gd, &gm, NULL) or install graphics.h drivers.
  2. Shapes Not Appearing

    • Cause: Coordinates out of bounds (x > getmaxx()).
    • Fix: Check getmaxx() and getmaxy() before drawing.
  3. Floodfill Not Working

    • Cause: Border color mismatch.
    • Fix: Ensure floodfill(x, y, border_color) uses the correct color.

Exam Tip

  1. Understand Coordinates: Always verify (x, y) ranges using getmaxx()/getmaxy().
  2. Step-by-Step Drawing: For questions like "Draw a house," break it into:
    • Rectangle (walls)
    • Triangle (roof)
    • Circle (door)
  3. Color Handling: Remember setcolor() must precede putpixel()/line().
  4. Animation: Use delay() to simulate real-time changes (e.g., moving objects).
  5. 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…