Top Banner
Graphics in C Language We will restrict our discussion on Graphics in C Language to 16 bit C programming and MS DOS environment. In a C Program first of all you need to initialize the graphics drivers on the computer. This is done using the initgraph method provided in graphics.h library. In the next few pages we will discuss graphics.h library in details. Important functions in graphic.h library will be discuees in details and samples programmes will be provided to show the power of C programming language. Graphics mode Initialization First of all we have to call the initgraph function that will intialize the graphics mode on the computer. initigraph have the following prototype. void initgraph(int far *graphdriver, int far *graphmode, char far *pathtodriver); Initgraph initializes the graphics system by loading a graphics driver from disk (or validating a registered driver) then putting the system into graphics mode.Initgraph also resets all graphics settings (color, palette, current position, viewport, etc.) to their defaults, then resets graphresult to 0. *graphdriver Integer that specifies the graphics driver to be used. You can give graphdriver a value using a constant of the graphics_drivers enumeration type. *graphmode Integer that specifies the initial graphics mode (unless *graphdriver = DETECT). If *graphdriver = DETECT, initgraph
24

Graphics in C Language

Apr 07, 2015

Download

Documents

Zarnigar Altaf
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Graphics in C Language

Graphics in C LanguageWe will restrict our discussion on Graphics in C Language to 16 bit C programming and MS DOS environment. In a C Program first of all you need to initialize the graphics drivers on the computer. This is done using the initgraph method provided in graphics.h library. In the next few pages we will discuss graphics.h library in details. Important functions in graphic.h library will be discuees in details and samples programmes will be provided to show the power of C programming language.

Graphics mode Initialization

First of all we have to call the initgraph function that will intialize the graphics mode on the computer. initigraph have the following prototype.

void initgraph(int far *graphdriver, int far *graphmode, char far *pathtodriver);

Initgraph initializes the graphics system by loading a graphics driver from disk (or validating a registered driver) then putting the system intographics mode.Initgraph also resets all graphics settings (color, palette, current position, viewport, etc.) to their defaults, then resets graphresult to 0.

*graphdriver

Integer that specifies the graphics driver to be used. You can give graphdriver a value using a constant of the graphics_drivers enumeration type.

*graphmode

Integer that specifies the initial graphics mode (unless *graphdriver = DETECT). If *graphdriver = DETECT, initgraph sets *graphmode to the highest resolution available for the detected driver. You can give *graphmode a value using a constant of the graphics_modes enumeration type.

*pathtodriver

Specifies the directory path where initgraph looks for graphics drivers (*.BGI) first.

1. If they're not there, initgraph looks in the current directory. 2. If pathtodriver is null, the driver files must be in the current directory.

*graphdriver and *graphmode must be set to valid graphics_drivers and graphics_mode values or you'll get unpredictable results. (The exception is graphdriver = DETECT.)

Page 2: Graphics in C Language

After a call to initgraph, *graphdriver is set to the current graphics driver, and *graphmode is set to the current graphics mode. You can tell initgraph to use a particular graphics driver and mode, or to autodetect the attached video adapter at run time and pick the corresponding driver. If you tell initgraph to autodetect, it calls detectgraph to select a graphics driver and mode.

Normally, initgraph loads a graphics driver by allocating memory for the driver (through _graphgetmem), then loading the appropriate .BGI file from disk.As an alternative to this dynamic loading scheme, you can link a graphics driver file (or several of them) directly into your executable program file.

Here is a sample program that initializes the graphics mode in C Language.

#include <graphics.h>#include <stdlib.h>#include <stdio.h>#include <conio.h>int main(void){/* request auto detection */ int gdriver = DETECT, gmode, errorcode;/* initialize graphics mode */ initgraph(&gdriver, &gmode, "");/* read result of initialization */ errorcode = graphresult();if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* return with error code */ }/* draw a line */ line(0, 0, getmaxx(), getmaxy());/* clean up */ getch(); closegraph(); return 0;}

The graphics programming in c language is discussed in brief to provide an over view to the beginner.

/* Sample program to draw a circle*/#include<graphics.h>#include<conio.h>main(){ int gd=DETECT,gm; initgraph(&gd,&gm,""); /* initialization of graphic mode */ circle(150,150,100); getch(); closegraph(); /* Restore orignal screen mode */

Page 3: Graphics in C Language

}/* End of program */

Normally the screen which u view in DOS is in the text mode which means it is meant for text. And for graphics u need to initialize graphics mode. And for this to happen u need to include ?graphics.h?.

circle(x coordinate ,y coordinate , radius);

The circle command takes a X coordinate which means Vertical axis and Y coordinate which means Horizontal axis. And the last one is the radius of the circle. closegraph();

With out this function the screen mode will still remain in graphic mode and when u come out, to DOS u will see a different screen, which is not in the text mode.

/*A program to draw a space with stars*/#include<graphics.h>main(){ int gd=DETECT,gm; int i,x,y; initgraph(&gd,&gm,""); line(0,0,640,0); line(0,0,0,480); line(639,0,639,480); line(639,479,0,479); for(i=0;i<=1000;i++) { x=rand()%639; y=rand()%480; putpixel(x,y,15); } getch(); closegraph();}/* End of program *//*Here a sample program to illustrate how to use BARS which are used for visual statistics */#include<graphics.h>main() { int gd=DETECT,gm,maxx,maxy,x,y,button; initgraph(&gd,&gm,""); line(80,150,200,150); line(80,150,80,50); settextstyle(1,HORIZ_DIR,1); outtextxy(100,153,"<-X axis"); settextstyle(1,VERT_DIR,1); outtextxy(60,50,"<-Y axis"); bar(100,100,120,150); bar(130,120,150,150); getch(); closegraph();}

Page 4: Graphics in C Language

Turbo C graphics Programming

Harsha

                To start with graphics programming, Turbo C is a good choice. Even though DOS has its own limitations, it is having a large number of useful functions and is easy to program. To implement graphics algorithms, To give graphical display of statistics, To   view signals from any source, we can use C graphics. Here is a article to start programming with Turbo C. 'Run and Learn' is our method. We   have used source codes throughout the explanations. Just execute them to understand what is happening.

Visit Downloads page for free source codes of graphics programs.

            Turbo C has a good collection of graphics libraries. If you know the basics of C, you can easily learn graphics programming. To start programming, let us write a small program that displays a circle on the screen.

/*  simple.c    example 1.0*/#include<graphics.h>#include<conio.h>

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

    initgraph(&gd, &gm, "c:\\turboc3\\bgi " );    circle(200,100,150);

    getch();    closegraph();} 

    To run this program, you need graphics.h header file, graphics.lib library file and Graphics driver (BGI file) in the program folder. These files are part of Turbo C package. In all our programs we used 640x480 VGA monitor. So all the programs are according to that specification. You need to make necessary changes to your programs according to your screen resolution. For VGA monitor, graphics driver used is EGAVGA.BGI.

Page 5: Graphics in C Language

    Here, initgraph() function initializes the graphics mode and clears the screen. We will study the difference between text mode and graphics mode in detail latter.

InitGraph:

Initializes the graphics system.

Declaration:void far initgraph(int far *graphdriver, int far *graphmode, char far *pathtodriver);

Remarks: To start the graphics system, you must first call initgraph.

initgraph initializes the graphics system by loading a graphics driver from disk (or validating a registered driver) then putting the system into graphics mode.

initgraph also resets all graphics settings (color, palette, current position, viewport, etc.) to their defaults, then resets graphresult to 0.Arguments:

*graphdriver: Integer that specifies the graphics driver to be used. You can give graphdriver a value using a constant of the graphics drivers enumeration type.

*graphmode : Integer that specifies the initial graphics mode (unless *graphdriver = DETECT). If *graphdriver = DETECT, initgraph sets *graphmode to the highest resolution available for the detected driver. You can give *graphmode a value using a constant of the graphics_modes enumeration type.

pathtodriver : Specifies the directory path where initgraph looks for graphics drivers (*.BGI) first.  If they're not there, initgraph looks in the current directory.  If pathtodriver is null, the driver files must be in the current directory.  This is also the path settextstyle searches for the stroked character font files (*.CHR).

    closegraph() function switches back the screen from graphcs mode to text mode. It clears the screen also. A graphics program should have a closegraph function at the end of graphics. Otherwise DOS screen will not go to text mode after running the program. Here, closegraph() is called after getch() since screen should not clear until user hits a key.

    If you have the BGI file in the same folder of your program, you can just leave it as "" only. you need not mention *graphmode if you give *graphdriver as DETECT.

Page 6: Graphics in C Language

    To get details of different graphics modes and graphics drivers, view appendix.

    In graphics mode, all the screen co-ordinates are mentioned in terms of pixels. Number of pixels in the screen decides resolution of the screen. In the example 1.0,  circle is drawn with x-coordinate of the center 200, y-coordinate 100 and radius 150 pixels. All the coordinates are mentioned with respect to top-left corner of the screen.

Basic Shapes and Colors:

    Now let us write a program to draw some basic shapes.

/*shapes.cexample 1.1*/

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

void main(){    int gd=DETECT, gm;    int poly[12]={350,450, 350,410, 430,400, 350,350, 300,430, 350,450 };    initgraph(&gd, &gm, "");          circle(100,100,50);    outtextxy(75,170, "Circle");    rectangle(200,50,350,150);     outtextxy(240, 170, "Rectangle");    ellipse(500, 100,0,360, 100,50);    outtextxy(480, 170, "Ellipse");    line(100,250,540,250);    outtextxy(300,260,"Line");

    sector(150, 400, 30, 300, 100,50);    outtextxy(120, 460, "Sector");    drawpoly(6, poly);    outtextxy(340, 460, "Polygon");    getch();    closegraph();}

Page 7: Graphics in C Language

Here is the screenshot of output:

    Here, circle() function takes x, y coordinates of the circle with respect to left top of the screen and radius of the circle in terms of pixels as arguments. Not that, in graphics, almost all the screen parameters are measured in terms of pixels.

    Function outtextxy() displays a string in graphical mode. You can use different fonts, text sizes, alignments, colors and directions of the text that we will study later. Parameters passed are x and y coordinates of the position on the screen where text is to be displayed. There is another function outtext() that displayes a text in the current position. Current position is the place where last drawing is ended. These functions are declared as follows:

void far outtextxy(int x, int y, char *text);void far outtext(char *text);

Circle, arc, pieslice are declared as follows:

Page 8: Graphics in C Language

Declaration:  void far arc(int x, int y, int stangle, int endangle, int radius);  void far circle(int x, int y, int radius);  void far pieslice(int x, int y, int stangle, int endangle, int radius);

Remarks:

arc draws a circular arc in the current drawing color. circle draws a circle in the current drawing color. pieslice draws a pie slice in the current drawing color, then fills it using

the current fill pattern and fill color.

Arguments:

(x,y): Center point of arc, circlew, or pie slice stangle: Start angle in degrees endangle: End angle in degrees

radius: Radius of arc, circle, and pieslice

    Here, stangle and endangle are in degrees starting from the +ve x-axis in the polar coordinate system in the anti-clockwise direction. if stangle is 0, endangle is 360, it will draw a full circle. Refer this figure for clear idea: For the details of current color, fill color and fill patterns, refer the sections Lines and Colors.

Page 9: Graphics in C Language

    Another basic shape that we come across is a rectangle. To draw a border, use rectangle with the coordinates of outline, to draw a square use rectangle with same height and width. drawpoly() and fillpoly() are two functions useful to draw any polygons. To use these functions, store coordinates of the shape in an array and pass the address of array as an argument to the function. By looking at the output of the previous program, you can understand what drawpoly is. fillpoly is similar except that it fills in the shape with current fill color.

Declaration:

void far rectangle(int left, int top, int right, int bottom); void far drawpoly(int numpoints, int far *polypoints); void far fillpoly(int numpoints, int far *polypoints);

Remarks:

rectangle draws a rectangle in the current line style, thickness, and drawing color.

drawpoly draws a polygon using the current line style and color.

fillpoly draws the outline of a polygon using the current line style and

Page 10: Graphics in C Language

color, then fills the polygon using the current fill pattern and fill color.

Arguments:  

(left,top) is the upper left corner of the rectangle, and (right,bottom) is its lower right corner.

 numpoints:  Specifies number of points

*polypoints: Points to a sequence of (numpoints x 2) integers. Each pair of integers gives the x and y coordinates of a point on the polygon.

        To draw a closed polygon with N points, numpoints should be N+1 and the array polypoints[] should contain 2(N+1) integers with first 2 integers equal to last 2 integers.

        Let us study more about shapes latter. Here is some idea about colors. There are 16 colors declared in graphics.h as listed bellow.

BLACK:                  0 BLUE:                     1 GREEN:                  2CYAN:                    3 RED:                       4 MAGENTA:            5 BROWN:                 6LIGHTGRAY:         7 DARKGRAY:          8LIGHTBLUE:           9LIGHTGREEN:       10 LIGHTCYAN:         11LIGHTRED:            12 LIGHTMAGENTA: 13YELLOW:               14WHITE:                   15

        To use these colors, use functions setcolor(), setbkcolor() and setfillstyle(). setcolor() function sets the current drawing color. If we use setcolor(RED); and draw any shape, line or text after that, the drawing will be in red color. You can either use color as defined above or number like setcolor(4);. setbkcolor() sets background color for drawing. Setfillstyle sets fill pattern and fill colors. After

Page 11: Graphics in C Language

calling setfillstyle, if we use functions like floodfill, fillpoly, bar etc, shpes will be filled with fill color and pattern set using setfillstyle. These function declarations are as follows.

Declaration:  void far setfillstyle(int pattern, int color); void far setcolor(int color); void far setbkcolor(int color);

Remarks:

setfillstyle sets the current fill pattern and fill color. setcolor sets the current drawing color to color, which can range from 0 to

getmaxcolor.

setbkcolor sets the background to the color specified by color.

        The parameter pattern in setfillstyle is as follows:

 Names Value Means  Fill With...

EMPTY_FILL 0 Background color

SOLID_FILL 1 Solid fill

LINE_FILL 2 ---

LTSLASH_FILL 3 ///

SLASH_FILL 4 ///, thick lines

BKSLASH_FILL 5 \\\, thick lines

LTBKSLASH_FILL 6  \\\

HATCH_FILL 7 Light hatch

XHATCH_FILL 8 Heavy crosshatch

INTERLEAVE_FILL

9 Interleaving lines

WIDE_DOT_FILL 10 Widely spaced dots

CLOSE_DOT_FILL 11 Closely spaced dots

USER_FILL 12 User-defined fill pattern

        Here is an example program with colors, pixels, bar, cleardevice etc. stdlib.h is used for random number generation. We have a function random(no), it returns a random number between 0 an no. The effect is by drawing random radius, random color circles with same center and random pixels. kbhit()

Page 12: Graphics in C Language

function(defined in conio.h) returns a nonzero value when a key is pressed in the keyboard. So, the loop will continue until a key is pressed.

/*random.csome graphics effects using random numbers.example 1.2by HarshaPerla, http://eharsha.tk*/

#include "graphics.h"#include "conio.h"#include "stdlib.h"

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

    initgraph(&gd, &gm, "");    setcolor(3);    setfillstyle(SOLID_FILL,RED);    bar(50, 50, 590, 430);        setfillstyle(1, 14);    bar(100, 100, 540, 380);

    while(!kbhit())    {        putpixel(random(439)+101,  random(279)+101,random(16));        setcolor(random(16));        circle(320,240,random(100));    }    getch();    closegraph();}

 

 

 

Page 13: Graphics in C Language

In the next part of the article, Ranjith K. H. will explain about adding mouse to your application. Read Part II

Tell us about this article: This is the first article of this tutorial. We are planning to expand it. To continue with, We need your suggestions. Next part of the article will be depending on the comments you post. Tell us which part of the article need to be explained more, how can the article be elaborated more and how did you feel the article. Click here to post a feed back or e-mail me:  [email protected]

->Mouse Programming with Turbo C

http://electrosofts.com/cgraphics/

In GUI's like Windows, mouse is very important for user interaction. But in DOS, mouse will come in to picture only in some of the programs. If you are writing DOS games or graphics programs, you can add mouse functionality to your

code. Here is how to do that.

If you are beginner to Turbo C graphics programming, read our introduction to Turbo C graphics.

           Mouse can be used in text mode as well as in graphics mode. Usually it is used in graphics mode. Hence we must first change over to graphics mode. In our program the function initgraph() is responsible for switching the mode from text to graphics .DETECT is a macro defined in 'graphics.h'. It requests initgraph() to automatically determine which graphics driver to load in order to switch to the highest resolution graphics mode. The initgraph() function takes three parameters, the graphics driver, the graphics mode and the path to the driver file.

           Once the driver has been loaded, initgraph() sets up the numeric values of the graphics mode chosen in the variables gd and gm respectively. Here we are assuming that the driver files are in the directory 'c:\tc\bgi'. Hence the path passed to initgraph() is 'c:\tc\bgi'.

            The various mouse functions can be accessed by setting up the AX register with different values (service number) and issuing interrupt number 51. The functions are listed bellow

Interrupt Service Purpose

51 

 Reset mouse and get status Call with AX = 0

Page 14: Graphics in C Language

 Returns:  AX = FFFFh If mouse support is available               Ax = 0 If mouse support is not available 

51 1 Show mouse pointer  Call with AX = 1   Returns: Nothing

51 2 Hide mouse pointer Call with AX = 2  Returns: Nothing

51 3

 Get mouse position and button status  Call with AX = 3  Returns: BX = mouse button status Bit   Significance  0     button not pressed  1     left button is pressed   2     right button is pressed  3     center button is pressed        CX = x coordinate DX = y coordinate

51 4

 Set mouse pointer position   Call with AX = 4 CX = x coordinate DX = y coordinate  Returns: Nothing

51 7

 Set horizontal limits for pointer Call with AX = 7 CX = minimum x coordinate DX = maximum x coordinate  Returns: Nothing

51 8

 Set vertical limits for pointer Call with AX = 8 CX = minimum y coordinate DX = maximum y coordinate  Returns: Nothing

 

 

Page 15: Graphics in C Language

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

       Let us consider a program which makes use of the above functions.

       #include<graphics.h>

Page 16: Graphics in C Language

       #include<stdio.h>       #include<conio.h>       #include<dos.h>       union REGS in,out;

       int callmouse()       {              in.x.ax=1;              int86(51,&in,&out);              return 1;       }       void mouseposi(int &xpos,int &ypos,int &click)       {               in.x.ax=3;              int86(51,&in,&out);              click=out.x.bx;              xpos=out.x.cx;              ypos=out.x.dx;        }       int mousehide()       {              in.x.ax=2;              int86(51,&in,&out);              return 1;       }      void setposi(int &xpos,int &ypos)      {              in.x.ax=4;             in.x.cx=xpos;             in.x.dx=ypos;             int86(51,&in,&out);      }     int main()      {             int x,y,cl,a,b;             clrscr();             int g=DETECT,m;             initgraph(&g,&m,"c:\tc\bgi");             a=100;             b=400;             setposi(a,b);             callmouse();             do             {                    mouseposi(x,y,cl);                    gotoxy(10,9);

Page 17: Graphics in C Language

                    printf("\n\tMouse Position is: %d,%d",x,y);                    printf("\n\tClick: %d",cl);                    printf("\n\tPress any key to hide the mouse");             }while(!kbhit());             getch();             mousehide();             printf("\n\n\tPress any key to Exit");             getch();     }

 

 The above program makes use of the following functions:

callmouse( ) mouseposi( )

mousehide( )

setposi( )

     callmouse()  :-  In this function AX is set to "1". When this function is called in main() it displays the mouse pointer. The position of the pointer can be changed by using the mouse.

     mousehide() :-  In this function AX is set to "2".When this function is called in main() it hides the mouse pointer. This function is useful while drawing  figures, first the mouse pointer is kept hidden, then the figure is been drawn and again the mouse pointer is been called.

     mouseposi() :-  In this function AX is set to "3". This function returns the position of the mouse pointer. It contains three parameters,they are xpos,ypos,click. xpos and ypos returns the position of x co-ordinate and y co-ordinate respectively. Click is the integer variable which returns the values 1,2,3 corresponding to the button pressed on the mouse and 0 for buttons being not pressed. If any key is pressed kbhit returns nonzero integer; if not it returns zero.

      setposi() :-      In this function AX is set to "4". This function sets the mouse pointer to specific position . CX is been loaded by x co-ordinate of the mouse pointer and DX is been loaded with the y co-ordinate of the mouse pointer.

    Let us consider another program

         #include<graphics.h>

Page 18: Graphics in C Language

         #include<stdio.h>         #include<conio.h>         #include<dos.h>         union REGS in,out;

         int callmouse()          {                 in.x.ax=1;                 int86(51,&in,&out);                 return 1;          }         void restrictmouseptr(int x1,int y1,int x2,int y2)          {                 in.x.ax=7;                 in.x.cx=x1;                 in.x.dx=x2;                 int86(51,&in,&out);                 in.x.ax=8;                 in.x.cx=y1;                 in.x.dx=y2;                 int86(51,&in,&out);          }         int main()          {                  int x,y,cl,a,b;                 clrscr();                 int g=DETECT,m;                 initgraph(&g,&m,"c:\tc\bgi");                 rectangle(100,100,550,400);                 callmouse();                 restrictmouseptr(100,100,550,400);                 getch();          }

            The above program makes use of the following functions:

Horizontal ( ) Vertical( )

      Horizontal() :- In this function AX is set to "7". Its sets the horizontal barrier for the pointer which restricts the mouse pointer to pass that limit. CX is been loaded with the minimum x co-ordinate and Dx is been loaded with the maximum x co-ordinate.

     Vertical() :-     In this function AX is set to "8".Its sets the vertical barrier for the pointer which restricts the mouse pointer to pass that limit. CX is been loaded

Page 19: Graphics in C Language

with the minimum y co-ordinate and Dx is been loaded with the maximum y co-ordinate.