Back

Graphics Program In C

30 Dec 2024
10 min read

Graphics program in C is a way to create visual elements and animations using the C programming language. With graphics programming in C, the field of graphics opens to developers, allowing them to create graphics, animation, and even applications equipped with a set of tools. From simple geometric shapes to intricate user interface concepts, they are best when transformed into engaging visuals. It is not only essential or beneficial to learn the basics of graphics programming in C, but it is crucial to acquire the knowledge of setting the basis for visually developed applications. In this article, we’ll start with the fundamentals of C for graphics, then move on to reveal why it matters and the exclusive features and applications that make it work.

What is the Graphics Program in C

C graphic programming is a method of creating visual elements, such as shapes, lines, and images, where the program uses rich utilities such as OpenGL, GDI, Allegro, etc., helping developers design anything from 2 to 3-D graphics to multimedia programs and games. It’s a blend of creativity and technical skill, requiring a solid grasp of programming fundamentals and the use of development environments like Code::Blocks or Visual Studio. The uses range across gaming, computer-aided design and drafting, data visualization, multimedia, interface design, animation, and special effects.

Libraries of Graphic Program in C

A C graphics library makes different libraries available to ease graphics development. Here are some of the most popular ones:

  • Graphics.h: graphics.h is a simple C library for basic 2D graphics like shapes and lines. It is perfect for beginners learning graphics programming. It’s easy to use but lacks support for modern graphics and 3D rendering. It mainly works with older compilers like Turbo C++. 
  • OpenGL: Strong and comprehensive C graphics library that allows the creation of the best 3D graphics. It offers an enormous range of tools for rendering 3D objects and developing interactive applications.
  • Simple DirectMedia Layer (SDL): A multimedia cross-platform library built at the low level of hardware access meant for Direct3D, OpenGL, audio, keyboard, mouse, joystick, 2D graphic drawing, and graphical output. It is mostly used to create games and multimedia applications.
  • Allegro: Allegro is a relatively simple multimedia library for C/C++ that supports graphics, sound, and input devices, making it suitable for 2D game development.
  • GTK+ (GIMP Toolkit): An Object Oriented free software Development toolkit that can be used in making GUIs. 
  • Cairo: The best and probably the only fit is a vector graphics library that provides high-quality 2D graphics. Compatible with several output types, including PNG, PDF, and SVG, it is appropriate for both web graphics and print.
  • SFML (Simple and Fast Multimedia Library): The software library that can be incorporated into the formation of 2D/3D games and other multimedia products. It comes with simple interfaces for drawing graphics, controlling sounds, and managing input gadgets.
  • GLUT (OpenGL Utility Toolkit): An OpenGL library that helps create the window, input, and 3D graphics, which makes it easier to produce cross-platform applications.
  • Qt: A highly effective GUI platform for building graphic interfaces for graphical and haptic-based interfaces for desktops and mobile devices. 
  • DISLIN:  DISLIN is a powerful graphics library for data visualization. It is mainly used for scientific plotting and engineering applications. It supports various chart types, 2D/3D plots, and file export formats. It’s important to know that it's more focused on visualizing data than real-time rendering. Therefore, it is unsuitable for interactive graphics or game development.
  • GLFW: GLFW is a lightweight library for creating OpenGL-based 3D graphics applications. It handles window creation, input, and context management; therefore, it’s great for modern game development and simulations. However, it doesn't offer built-in GUI widgets or high-level graphics functions, which require additional libraries for advanced features.

Colors of C Language Graphics

Colors play an important role in graphics program in C by making programs visually engaging. Graphics libraries in C offer functions that manipulate and apply colors to the output. The most widely used scheme in C is the RGB (Red, Green, Blue) model. 

In the RGB color model, every color can be made by using a combination of red, green, and blue values. Each value ranges from 0 to 255, where 0 is no intensity and 255 is full intensity. For instance, red is represented by (255, 0, 0,), green by (0, 255, 0,), and blue by (0, 0, 255).

Combining these values allows you to create millions of unique colors for designing vibrant visuals. Many graphics libraries also offer predefined color constants to simplify implementation. 

You can set the color of graphical elements using functions from the graphics library. For instance, in the graphics.h library, the setcolor() function sets the drawing color. To set the color to red, you use:

set color(RED);

Once set, the subsequent graphical elements will be drawn in red. You can also create custom colors by specifying RGB values. For example, to create purple:

set color(COLOR(128, 0, 128));

It mixes red and blue to generate purple.

Color Macro Integer Value
BLACK (0, 0, 0)
BLUE (0, 0, 255)
GREEN (0, 255, 0)
CYAN (0, 255, 255)
RED (255, 0, 0)
MAGENTA (255, 0, 255)
BROWN (165, 42, 42)
LIGHT GRAY (211, 211, 211)
DARK GRAY (169, 169, 169)
LIGHT BLUE (173, 216, 230)
LIGHT GREEN (144, 238, 144)
LIGHT CYAN (224, 255, 255)
LIGHT RED (255, 160, 160)
LIGHT MAGENTA (255, 182, 193)
YELLOW (255, 255, 0)
WHITE (255, 255, 255)

Syntax of Graphics Program in C

The general syntax structure for a graphics program in C using the graphics.h library looks like this:

  1. #include <graphics.h>: Adds the graphics library for drawing functions.
  2. initgraph(&gd, &gm, NULL): Initializes graphics mode; gd detects the driver, gm sets the mode.
  3. Graphics Functions: Use functions like circle(), line(), or rectangle() to draw shapes.
  4. getch(): Waits for a key press before exiting.
  5. closegraph(): Closes the graphics mode and deallocates resources.
#include <graphics.h>	// Include the graphics library
#include <conio.h>   	// For getch() function (optional)
 
int main() {
    int gd = DETECT, gm; 	// Graphics driver and mode variables
 
    // Initialize the graphics mode
    initgraph(&gd, &gm, NULL);
 
    // Graphics functions to draw shapes or perform actions
    // Example: Drawing a circle
    circle(200, 200, 100);
 
    // Wait for user input before closing the window
    getch();
 
    // Close the graphics mode
    closegraph();
 
    return 0;
}

Basic Example of Graphics Program in C

Drawing A Circle

A basic graphics program in C involves setting up a graphics mode, drawing basic shapes, and then closing the graphics mode after the work is done. Below is a simple program that initializes the graphics mode and draws a circle:

#include <graphics.h>
#include <conio.h>   // For getch()

int main() {
    int gd = DETECT, gm;

    // Initialize graphics mode
    initgraph(&gd, &gm, NULL);

    // Draw a circle with center (300, 300) and radius 50
    circle(300, 300, 50);

    // Wait for user input before closing the window
    getch();

    // Close the graphics mode
    closegraph();

    return 0;
}

Output:

custom img

C Program to draw Circle, Triangle, Rectangle & Square

Here are C language graphics program examples for some basic shapes: 

Program for Circle:

#include<stdio.h>
#include<graphics.h>

int main(){
   int gd = DETECT,gm;
   int x ,y ,radius=80;
   initgraph(&gd, &gm, "C:\\TC\\BGI");
   /* Initialize center of circle with center of screen */
   x = getmaxx()/2;
   y = getmaxy()/2;

   outtextxy(x-100, 50, "CIRCLE Using Graphics in C");
   /* Draw circle on screen */
   circle(x, y, radius);

   closegraph();
   return 0;
}

Output:

custom img

Program for Triangle:

#include <graphics.h> 
#include <conio.h> 

// Driver code 
int main() 
{ 
	// gm is Graphics mode which 
	// is a computer display 
	// mode that generates 
	// image using pixels. 
	// DETECT is a macro 
	// defined in "graphics.h" 
	// header file 
	int gd = DETECT, gm; 

	// initgraph initializes 
	// the graphics system 
	// by loading a graphics 
	// driver from disk 
	initgraph(&gd, &gm, ""); 

	// Triangle 

	// line for x1, y1, x2, y2 
	line(150, 150, 450, 150); 

	// line for x1, y1, x2, y2 
	line(150, 150, 300, 300); 

	// line for x1, y1, x2, y2 
	line(450, 150, 300, 300); 

	// closegraph function closes 
	// the graphics mode and 
	// deallocates all memory 
	// allocated by graphics system 
	getch(); 

	// Close the initialized gdriver 
	closegraph(); 
} 

Output:

custom img

Program for rectangle:

// C program to draw a rectangle 
#include <graphics.h> 

// Driver code 
int main() 
{ 
	// gm is Graphics mode which is a computer display 
	// mode that generates image using pixels. 
	// DETECT is a macro defined in "graphics.h" header file 
	int gd = DETECT, gm; 

	// location of left, top, right, bottom 
	int left = 150, top = 150; 
	int right = 450, bottom = 450; 

	// initgraph initialises the graphics system 
	// by loading a graphics driver from the disk 
	initgraph(&gd, &gm, ""); 

	// rectangle function 
	rectangle(left, top, right, bottom); 

	getch(); 

	// closegraph function closes the graphics 
	// mode and deallocates all memory allocated 
	// by the graphics system
	closegraph(); 

	return 0; 
} 

Output:

custom img

Program for Square:

#include <graphics.h>
#include <conio.h>   // For getch()

int main() {
    int gd = DETECT, gm;

    // Initialize graphics mode
    initgraph(&gd, &gm, NULL);

    // Coordinates for the top-left corner and size of the square
    int x1 = 200, y1 = 200;  // Top-left corner
    int side = 150;           // Length of the side of the square

    // Draw a square using the rectangle function (same as a rectangle)
    rectangle(x1, y1, x1 + side, y1 + side);

    // Wait for user input before closing the window
    getch();

    // Close the graphics mode
    closegraph();

    return 0;
}

Output:

custom img

Graphics Example Using Colours of C Language Graphics

A Coloured Circle and a Rectangle:

#include <graphics.h>
#include <conio.h>

int main() {
    int gd = DETECT, gm;
    
    // Initialize graphics mode
    initgraph(&gd, &gm, NULL);

    // Set color and draw a circle
    setcolor(RED);
    circle(200, 200, 100);

    // Set color and draw a rectangle
    setcolor(BLUE);
    rectangle(150, 150, 250, 250);

    // Wait for user input
    getch();

    // Close graphics mode
    closegraph();

    return 0;
}

Output:

custom img
custom img

Applications of Graphics Programming in C

  1. Game Development: Graphic programming is essential for games, as it provides opportunities to develop 2-D and 3-D graphics and to implement interactivity. 
  2. Computer-Aided Design (CAD): In CAD applications, graphics programming is used to model and control 2D and 3D objects. 
  3. Data Visualisation: Graphics programming transforms data into graphical information such as charts, graphs, or diagrams. 
  4. Image Processing: C for graphics programming helps in activities such as image Enhancement, Filtering and manipulation. 
  5. Graphical User Interfaces (GUIs): Graphics programming involves developing interactive and welcoming interfaces in software programs. 
  6. Simulations and Visualisations: It creates simulations and visualises real-world situations based on physical simulation, simulations in science, and more.
  7. Embedded Systems: Graphics programming is used in embedded systems to realise effective graphical outputs and inputs for devices such as smart appliances and medical instruments.

Pros and Cons of Graphics Program

Here are some of the pros and cons of graphics programs in C:

Pros: 

  • Enhanced Visual Appeal: Creates engaging and interactive visuals for applications like games and GUIs.
  • Real-Time Interactivity: Enables real-time user interaction with graphics, improving user experience.
  • Wide Application: Useful in diverse fields like gaming, CAD, simulations, and data visualisation.
  • Creativity: Offers endless possibilities for creative design and animation.
  • Hardware Access: Graphics libraries like OpenGL and SDL provide direct access to hardware for optimised performance.

Cons: 

  • Complexity: Requires advanced programming skills and understanding of graphical concepts.
  • Performance Demands: Can be resource-intensive, requiring powerful hardware for smooth performance.
  • Platform Dependency: Some libraries are platform-specific, limiting cross-platform compatibility.
  • Steep Learning Curve: Learning the intricacies of different graphics libraries can be challenging for beginners.
  • Debugging Challenges: Visual bugs can be harder to diagnose compared to traditional programming.

Conclusion

Learning C for graphics is fundamental to learning how things work at the most basic level. Graphics programming is included in the curriculum of learning for the initial level software developer to increase their versatility as well as expand the field of application. For instance, game development, simulation, and user interface applications all use graphic programming. Knowledge of the structure and ways to create object-oriented images enhances the developers’ possibilities to create more effective applications. To learn more and build a strong foundation, you can enroll in the CCBP Academy 4.0 program to become job-ready.

Frequently Asked Questions

1. What is graphics programming in C?

Graphics programming in C involves using libraries like OpenGL and SDL to create visual elements, shapes, and animations in software applications. It enables the development of interactive interfaces, games, and simulations.

2. What are the common graphics libraries in C?

Common graphics libraries in C include OpenGL, SDL, Allegro, and GTK+. These libraries provide tools to render 2D and 3D graphics, handle user input, and develop multimedia applications.

3. Do I need a special compiler for graphics programming in C?

Yes, to use graphics libraries like graphics.h, you may need a compiler that supports these libraries, such as Turbo C++ or Code::Blocks. Additionally, ensure you have the appropriate graphic library files set up in your IDE.

4. What is the difference between a circle and a rectangle in graphics programming?

In graphics programming, a circle is drawn using a center point and radius, while its top-left and bottom-right corners define a rectangle. Both shapes are fundamental to building more complex graphics.

5. Can I use graphics programming for game development in C?

Yes, graphics programming is widely used in game development for rendering 2D and 3D environments, characters, and special effects. Libraries like SDL and OpenGL are popular choices for building interactive games in C.

Read More Articles

Chat with us
Chat with us
Talk to career expert