Graphics Programming in C

In this chapter, we will delve into the exciting world of graphics programming using the C language. Graphics programming allows us to create visually appealing applications, ranging from simple shapes to complex images and animations. We will start from the basics and gradually move towards more advanced concepts, exploring various techniques along the way.

Introduction to Graphics Programming

Graphics programming involves creating and manipulating graphical elements on a screen. In C, we typically use libraries like Graphics.h or SDL for this purpose. These libraries provide functions to draw shapes, images, and text on the screen.

Note : Before starting please install the library and include it as header file in your C code

Basics of Graphics.h Library

Let’s start with a basic example using the Graphics.h library to draw a simple shape, like a rectangle, on the screen.

				
					#include <graphics.h>

int main() {
    int gd = DETECT, gm;
    initgraph(&gd, &gm, NULL);

    rectangle(100, 100, 200, 200);

    getch();
    closegraph();
    return 0;
}

				
			
				
					// Output //
This code will display a window with a rectangle drawn inside it.
				
			

Explanation:

  • #include <graphics.h>: This includes the graphics library header file.
  • int gd = DETECT, gm;: gd and gm are variables used by the library to initialize the graphics mode.
  • initgraph(&gd, &gm, NULL);: This initializes the graphics system.
  • rectangle(100, 100, 200, 200);: This draws a rectangle with coordinates (100,100) as the top-left corner and (200,200) as the bottom-right corner.
  • getch();: This waits for a key press before closing the window.
  • closegraph();: This closes the graphics system.

Understanding Coordinate System

In graphics programming, we work with a coordinate system where the origin (0,0) is typically at the top-left corner of the screen. Positive x-direction is towards the right, and positive y-direction is towards the bottom.

Drawing Basic Shapes

Now, let’s explore drawing various basic shapes such as lines, circles, and ellipses.

Drawing Lines

Drawing a line involves specifying the coordinates of its endpoints. Let’s draw a line from (50,50) to (200,200).

				
					#include <graphics.h>

int main() {
    int gd = DETECT, gm;
    initgraph(&gd, &gm, NULL);

    line(50, 50, 200, 200);

    getch();
    closegraph();
    return 0;
}

				
			
				
					// Output //
This code will display a window with a line drawn from (50,50) to (200,200).


				
			

Explanation:

  • line(50, 50, 200, 200);: This draws a line from (50,50) to (200,200).

Drawing Circles

Drawing a circle involves specifying the center coordinates and the radius. Let’s draw a circle with center (150,150) and radius 50.

				
					#include <graphics.h>

int main() {
    int gd = DETECT, gm;
    initgraph(&gd, &gm, NULL);

    circle(150, 150, 50);

    getch();
    closegraph();
    return 0;
}

				
			
				
					// Output //
This code will display a window with a circle drawn at (150,150) with a radius of 50.



				
			

Explanation:

  • circle(150, 150, 50);: This draws a circle with center at (150,150) and radius 50.

Drawing Ellipses

Drawing an ellipse requires specifying the center coordinates, major and minor axes lengths. Let’s draw an ellipse with center (200,150), major axis of 100, and minor axis of 50.

				
					#include <graphics.h>

int main() {
    int gd = DETECT, gm;
    initgraph(&gd, &gm, NULL);

    ellipse(200, 150, 0, 360, 100, 50);

    getch();
    closegraph();
    return 0;
}

				
			
				
					// Output //
This code will display a window with an ellipse drawn at (200,150).





				
			

Explanation:

  • ellipse(200, 150, 0, 360, 100, 50);: This draws an ellipse with center at (200,150), major axis of 100, and minor axis of 50.

Advanced Graphics Concepts

Now, let’s explore some advanced concepts in graphics programming, such as color manipulation, text rendering, and image handling.

Adding Colors

Graphics programming becomes more interesting when we introduce colors. We can use the setcolor() function to set the drawing color before drawing shapes.

				
					#include <graphics.h>

int main() {
    int gd = DETECT, gm;
    initgraph(&gd, &gm, NULL);

    setcolor(RED);
    circle(150, 150, 50);

    getch();
    closegraph();
    return 0;
}

				
			
				
					// output //
This code will display a window with a red circle.


				
			

Explanation:

  • setcolor(RED);: This sets the drawing color to red before drawing the circle.

Rendering Text

We can render text on the screen using the outtextxy() function.

				
					#include <graphics.h>

int main() {
    int gd = DETECT, gm;
    initgraph(&gd, &gm, NULL);

    outtextxy(100, 100, "Hello, Graphics Programming!");

    getch();
    closegraph();
    return 0;
}

				
			
				
					// output //
This code will display a window with the text rendered at (100,100).



				
			

Explanation:

  • outtextxy(100, 100, "Hello, Graphics Programming!");: This renders the text “Hello, Graphics Programming!” at coordinates (100,100).

Loading and Displaying Images

We can load and display images on the screen using the appropriate functions provided by the graphics library.

				
					#include <graphics.h>

int main() {
    int gd = DETECT, gm;
    initgraph(&gd, &gm, NULL);

    readimagefile("image.jpg", 100, 100, 300, 300);

    getch();
    closegraph();
    return 0;
}

				
			
				
					// output //
This code will display the image "image.jpg" within the specified coordinates.


				
			

Explanation:

  • readimagefile("image.jpg", 100, 100, 300, 300);: This loads the image “image.jpg” and displays it within the specified coordinates.

Interactive Graphics

One fascinating aspect of graphics programming is creating interactive graphics where user input drives the display. Let’s explore how to achieve this using mouse and keyboard events.

Handling Mouse Events

We can detect mouse events such as clicks and movements to create interactive graphics. Here’s a simple example that draws a circle wherever the user clicks the mouse.

				
					#include <graphics.h>

void drawCircleOnClick(int x, int y) {
    circle(x, y, 20);
}

int main() {
    int gd = DETECT, gm;
    initgraph(&gd, &gm, NULL);

    // Registering mouse click event handler
    setmouseclick(WM_LBUTTONDOWN, drawCircleOnClick);

    getch();
    closegraph();
    return 0;
}

				
			
				
					// output //
This code will display a graphics window, and whenever you click the left mouse button, a circle will be drawn at that position.
				
			

Explanation:

  • setmouseclick(WM_LBUTTONDOWN, drawCircleOnClick);: This registers a function drawCircleOnClick to be called whenever the left mouse button is clicked. The function draws a circle at the clicked position.

Handling Keyboard Events

Keyboard events can also be utilized to create interactive graphics. Here’s an example that changes the color of a circle based on keyboard input.

				
					#include <graphics.h>

void changeColorOnKeypress(char key) {
    if (key == 'r' || key == 'R')
        setcolor(RED);
    else if (key == 'g' || key == 'G')
        setcolor(GREEN);
    else if (key == 'b' || key == 'B')
        setcolor(BLUE);
}

int main() {
    int gd = DETECT, gm;
    initgraph(&gd, &gm, NULL);

    // Registering keyboard event handler
    while (1) {
        char key = getch();
        changeColorOnKeypress(key);
        circle(200, 200, 50); // Draw circle at fixed position
    }

    getch();
    closegraph();
    return 0;
}

				
			
				
					// output //
This code will continuously draw a circle at a fixed position (200, 200), and pressing 'r', 'g', or 'b' keys will change its color to red, green, or blue, respectively.


				
			

Explanation:

  • while (1): This creates an infinite loop to continuously check for keyboard input.
  • char key = getch();: This reads a character from the keyboard.
  • changeColorOnKeypress(key);: This function changes the drawing color based on the key pressed.

Loading and Displaying Images

We can load and display images on the screen using the appropriate functions provided by the graphics library.

				
					#include <graphics.h>

int main() {
    int gd = DETECT, gm;
    initgraph(&gd, &gm, NULL);

    readimagefile("image.jpg", 100, 100, 300, 300);

    getch();
    closegraph();
    return 0;
}

				
			

Explanation:

  • readimagefile("image.jpg", 100, 100, 300, 300);: This loads the image “image.jpg” and displays it within the specified coordinates.

Double Buffering

Double buffering is a technique used to reduce flickering in animations by drawing graphics off-screen before displaying them. Here’s a basic example demonstrating double buffering.

				
					#include <graphics.h>

int main() {
    int gd = DETECT, gm;
    initgraph(&gd, &gm, NULL);

    while (!kbhit()) {
        // Perform drawing operations off-screen
        cleardevice();
        circle(200, 200, 50);
        // Perform additional drawing operations

        // Swap buffers
        delay(100); // Introduce delay for visualization
        swapbuffers();
    }

    getch();
    closegraph();
    return 0;
}

				
			
				
					// output //
This code will continuously draw a circle with double buffering, resulting in smoother animation.



				
			

Explanation:

  • cleardevice();: This clears the off-screen buffer.
  • swapbuffers();: This swaps the off-screen buffer with the on-screen buffer.

Optimizing Drawing Operations

To improve performance, minimize the number of drawing operations by grouping similar shapes together or using more efficient algorithms.

				
					#include <graphics.h>

int main() {
    int gd = DETECT, gm;
    initgraph(&gd, &gm, NULL);

    // Grouping drawing operations
    setcolor(RED);
    circle(200, 200, 50);
    setcolor(BLUE);
    rectangle(150, 150, 250, 250);

    getch();
    closegraph();
    return 0;
}

				
			
				
					// output //
This code will display a red circle and a blue rectangle.



				
			

Explanation:

  • Grouping drawing operations reduces the overhead of setting color and other parameters multiple times.

In this chapter, we explored graphics programming in C from basic shapes to advanced concepts like interactive graphics and performance optimization. By mastering the techniques discussed here, you can create compelling graphical applications that engage users and deliver a rich visual experience.From drawing simple shapes to handling user input and optimizing performance, graphics programming in C offers endless possibilities for creativity and innovation. As you continue to explore and experiment with different techniques and libraries, you'll unlock even more potential for creating stunning graphics applications.Happy coding!❤️

Table of Contents