C Programming

Unit 11: Introduction to Graphics

Graphics modes, initialization, and basic graphics functions in C.

Modes

C programs operate in one of two display modes:

  • Text mode — the screen displays only characters (rows and columns of text).
  • Graphics mode — the screen displays pixels, allowing drawing of points, lines, and shapes.

To use graphics, the program must switch from text mode to graphics mode. The graphics functions used here are defined in the <graphics.h> header file provided with the Turbo C / Borland C compiler.

Initialization

Before drawing anything, the graphics system must be initialized using the initgraph() function.

Syntax:

void initgraph(int *graphdriver, int *graphmode, char *pathtodriver);
  • graphdriver — graphics driver to be used (usually DETECT to auto-detect).
  • graphmode — graphics mode (set by initgraph when DETECT is used).
  • pathtodriver — path to the BGI driver files.

Example — initializing graphics:

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

int main(void)
{
    int gd = DETECT, gm;
    initgraph(&gd, &gm, "C:\\TURBOC3\\BGI");

    /* drawing code goes here */

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

The closegraph() function restores the system to text mode and releases memory used by the graphics system.

Graphics functions

The graphics library provides a number of built-in functions to draw shapes and write text.

FunctionPurpose
initgraph(&gd, &gm, path)Initializes graphics mode.
closegraph()Closes graphics mode.
putpixel(x, y, color)Draws a single pixel.
line(x1, y1, x2, y2)Draws a line between two points.
circle(x, y, radius)Draws a circle.
rectangle(x1, y1, x2, y2)Draws a rectangle.
ellipse(x, y, stangle, endangle, xrad, yrad)Draws an ellipse / arc.
arc(x, y, stangle, endangle, radius)Draws an arc.
setcolor(color)Sets the current drawing color.
setbkcolor(color)Sets the background color.
outtextxy(x, y, "text")Displays a string at the given pixel.
getmaxx(), getmaxy()Return maximum screen coordinates.

Example — drawing basic shapes:

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

int main(void)
{
    int gd = DETECT, gm;
    initgraph(&gd, &gm, "C:\\TURBOC3\\BGI");

    setcolor(WHITE);
    line(100, 100, 300, 100);
    rectangle(100, 150, 300, 250);
    circle(400, 200, 50);
    outtextxy(150, 300, "Graphics in C");

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