En el modo gráfico existe una enorme cantidad de funciones que realizan desde la tarea mas sencilla como es pintar un píxel, hasta la tarea mas compleja como pudiera ser dibujar un carácter por medio de trazos.

 

Para trabajar el modo gráfico es necesario incluir la librería graphics.h como hacer uso de la BGI (Borlan Graphics Interphase)

 

Para usar cualquier función es necesario colocar el adaptador de video en modo grafico y esto se logra a través de la función initgraph(); y al terminares necesario regresar al modo original a través de la función closegraph();

 

Para iniciar un programa en ambiente gráfico es recomendable correr una subrutina de inicialización de gráficos y detección de errores.

 

Algunos ejemplos de las funciones que se pueden encontrar en la librería de gráphics.h son:

Line(); circle(); arc(); elipse();rectangle(); ottextxy(); putpixel();

Para saber mas de las funciones de la librería de gráficos lo pueden buscar en el índice de turbo c

 

NOTA: Para dar de alta en tu computadora el modo de gráficos tienes que hacer los siguientes pasos: OPTIONS ->LINKER->LIBRARIE->seleccionar GRAPHICS LIBRARY

EJEMPLO:

#include<graphics.h>

#include<conio.h>

#include<math.h>

int main(void)

{

 clrscr();

 

 double fx;

 int graphdriver=DETECT,graphmode;

 initgraph(&graphdriver,&graphmode,"..\\bgi");

 outtextxy(30,30,”GRAFICACION DE SENO “);

 setbkcolor(RED);

 for (int x=0;x<=90;x++)

 {

   fx=(1+sin(x))*40+200;

  putpixel(x*15,fx,YELLOW);

  }

  setcolor(BLUE);

 line(310,100,310,400);

 line(100,240,500,240);

  getch();

  closegraph();

 return 0;

}

 

 

 

ESTRUCTURA DEL PROGRAMA

 

#include <graphics.h>  

#include <stdlib.h>

#include <stdio.h>

#include <conio.h>

 

int main(void)

{

   VARIABLES PARA INICIALIZAR MODO GRAFICO

   int gdriver = DETECT, gmode, errorcode;

 

   INICIALIZAR MODO GRAFICO

   initgraph(&gdriver, &gmode, "");

 

  DETECTA SI HAY ALGUN ERROR PARA USAR MODO GRAFICO

   errorcode = graphresult();

  

   if (errorcode != grOk)

   {

      printf("Graphics error: %s\n", grapherrormsg(errorcode));

      printf("Press any key to halt:");

      getch();

      exit(1);

   }

 

   line(0, 0, 50,50 ); DIBUJA UNA LINEA

 

   getch();

   closegraph(); CERRAR MODO GRAFICO

   return 0;

}

 

FUNCIONES PARA DIBUJAR

 

cleardevice(void); LIMPIA LA PANTALLA

 

setcolor(int color); COLOR DE LINEA

 

setbkcolor(int color); COLOR DE FONDO (PANTALLA)

 

480

 

TAMAÑO O RESOLUCION DE LA PANTALLA  640X480 PIXELS

640

 
 

 

 


line(int x1, int y1, int x2, int y2); DIBUJA UNA LINEA

 

rectangle(int left, int top, int right, int bottom); DIBUJA UN RECTANGULO

rectangle(izqierda,arriba,derecha,abajo);

 

putpixel(int x, int y, int color); PINTA UN PIXEL

 

outtextxy(int x, int y, char far *textstring); DIBUJA TEXTO

outtextxy(100,100,”Programa 1”);

 

settextstyle(int font, int direction, int charsize); TIPO DE LETRA A USAR

settextstyle(tipo letra, direccion, tamaño letra);

 

TIPOS DE LETRA (FONT)

 

0   DEFAULT_FONT       

1   TRIPLEX_FONT        

2   SMALL_FONT            

3   SANS_SERIF_FONT  

4   GOTHIC_FONT           

 

DIRECTION

 

0   HORIZ_DIR   

1   VERT_DIR    

 

settextjustify(int horiz, int vert); JUSTIFICAR TEXTO

 

HORIZ  

 

0   LEFT_TEXT     IZQUIERDA

1   CENTER_TEXT   CENTRADO

2   RIGHT_TEXT   DERECHA

 

VERT   

 

0   BOTTOM_TEXT  ABAJO

1   CENTER_TEXT   CENTRADO

2   TOP_TEXT      ARRIBA

 

RELLENADO DE FIGURAS

 

floodfill(int x, int y, int border); RELLENAR FIGURA

 

setfillstyle(int pattern, int color); TIPO DE RELLENO Y COLOR A USAR

 

TIPOS DE RELLENADO(FILL PATTERNS)

 

0   EMPTY_FILL       

1   SOLID_FILL       

2   LINE_FILL        

3   LTSLASH_FILL     

4   SLASH_FILL       

5   BKSLASH_FILL     

6   LTBKSLASH_FILL   

7   HATCH_FILL       

8   XHATCH_FILL      

9   INTERLEAVE_FILL  

10 WIDE_DOT_FILL   

11 CLOSE_DOT_FILL  

12 USER_FILL       

 

COLORES

 

0   BLACK         

1   BLUE          

2   GREEN          

3   CYAN          

4   RED           

5   MAGENTA       

6   BROWN         

7   LIGHTGRAY     

8   DARKGRAY      

9   LIGHTBLUE     

10 LIGHTGREEN   

11 LIGHTCYAN    

12 LIGHTRED     

13 LIGHTMAGENTA 

14 YELLOW       

15 WHITE         

128  BLINK       

 

EJEMPLO DE ANIMACION

 

#include <graphics.h>

#include <stdlib.h>

#include <stdio.h>

#include <conio.h>

#include <dos.h>

 

// EJEMPLO DE ANIMACION

 

int main(void)

{

   int gdriver = DETECT, gmode, errorcode;//variables para detectar modo grafico

   int x1,x2,y1,y2,x,y; //variables para tama¤o de la figura y para moverla

   clrscr();

   initgraph(&gdriver, &gmode, ""); //inicializar modo grafico

   errorcode = graphresult();

   if (errorcode != grOk) //detecta si hay algun error

   {

      printf("Graphics error: %s\n", grapherrormsg(errorcode));

      printf("Press any key to halt:");

      getch();

      exit(1);

   }

 

   x1=1;x2=100;y1=1;y2=100;x=3;y=3; //valores para las variables

 

   //dibuja un cuadro relleno

   setcolor(2); //color de linea

   setfillstyle(1,2); //tipo de rellenado y color

   rectangle(x1,y1,x2,y2); //dibujar cuadrado

   floodfill(x,y,2); //rellena la figura. Los valores de "x" y "y" deben

                             //estar dentro de la figura a rellenar

   getch();

   //animacion

   for(int i=0;i<=640;i++)

   {

     cleardevice(); //limpia la pantalla

     setcolor(2);

     setfillstyle(1,2);

     rectangle(x1+i,y1,x2+i,y2);//sumamos "i" a los valores de x1 y x2 para mover la figura

     floodfill(x+i,y,2);

     delay(5); //tiempo que tarda en repetir el ciclo

   }

 

   getch();

   closegraph();//cerrar modo grafico

   return 0;

}

 

 

 

Cuando utilizamos gráficos  usamos coordenadas ”x”  y  “y” y se mide en píxeles en c standard   y dependiendo de la computadora ,”x” tiene un máximo de “639”, y tiene un máximo de 479.

 

El modo para inicializar gráficos es :

 

Int gdriver=DETECT,gmode;

Initgraph(&gdriver,&gmode,”dirección de la carpeta bgi de tc”);

 

Existen varias funciones estándar con las que podemos trabajar en gráficos:

 

Cleardevice();  //limpia pantalla

Setbkcolor( int Color); // pone el color de fondo de la pantalla

Setcolor( int color); //elige el color  de los trazos que se agan

 

BLACK          0 

BLUE           1 

GREEN          2 

CYAN           3 

RED            4 

MAGENTA        5 

BROWN          6 

LIGHTGRAY      7 

DARKGRAY       8 

LIGHTBLUE      9 

LIGHTGREEN    10 

LIGHTCYAN     11 

LIGHTRED      12 

LIGHTMAGENTA  13 

YELLOW        14 

WHITE                15

 

Line(int x1, int y1, int x2, int y2); //hace una linea

Circle(int x, int y, int radio);  //hace un circulo;

Ellipce(int x, int y, int angulo inicial, int angulo final); //hace una elipse

Rectangle(int x izq,int y izq superior, int x der, int y der inferior); //hace un rectángulo

Putpixel(int x, int y ,int color); //pone un pixel

 

Settextstyle(int tipo de letra, int orientación, int tamaño);

 

Orientación   o  horizontal, 1  vertical

Tipo de letra:  0           DEFAULT_FONT

1                    TRIPLEX_FONT

2                    SMALL_FONT

3                    SAN_SERIF_FONT

4                    GOTHIC_FONT

 

 

Outtextxy(int x, int y,” texto”);

 

Setfillstylke(int tipo de relleno, in t color); //selecciona el color y tipo de relleno

 

Floodfill(int x, int y, int color dentro del que se va a rellenar);//rellena dando las

coordenadas dentro de la figura a rellenar;

EMPTY_FILL      ³  0  ³

SOLID_FILL      ³  1  ³

LINE_FILL       ³  2  ³

LTSLASH_FILL    ³  3  ³

SLASH_FILL      ³  4  ³

BKSLASH_FILL    ³  5  ³

LTBKSLASH_FILL  ³  6  ³

HATCH_FILL      ³  7  ³

XHATCH_FILL     ³  8  ³

INTERLEAVE_FILL ³  9  ³

WIDE_DOT_FILL   ³ 10  ³

CLOSE_DOT_FILL  ³ 11  ³

USER_FILL       ³ 12  ³

 

 

 

Y 0

 

X 0

Para poder graficar una función debemos tener en cuanta que  el eje y esta invertido a como lo necesitamos:

 

 

 

 

 

 

 

Primero trazamos los ejes donde vamos a graficar, supongamos que las coordenadas de intersección entre las líneas  es (449,159)  esto significa que este es nuestro origen 0

 

Usando la función  “ double evaluafuncion(char [], double);”

Evaluamos nuestra función  utilizando un ciclo, en donde se incremente el valor double que le enviamos a nuestra función.

 

 

double result;

a=0.0;

Ciclo

{

a=a+.01; por ejemplo.

evaluarfuncion(función ,a)

result=result*-1; //por que este es el valor del eje y que esta invertido

putpixel((a*escala)+449,(result*escala)+159,int color);

}

y este es el principio básico para poder graficar una función.

 

Existe diferentes formas para poder hacer una animación.

 

Una de las mas sencillas es hacer un algoritmo de incremento de coordenadas combinado con limpieza de pantalla , dentro de un ciclo.

 

      for(int k=0;k<50;k++)

      {

      cleardevice();//borra pantalla

      setcolor(LIGHTBLUE);//elije el color para las líneas

      line(26*k*.1,36*k*.1,76*k*.1,36*k*.1);

      line(26*k*.1,36*k*.1,16*k*.1,46*k*.1);

      line(76*k*.1,36*k*.1,76*k*.1,46*k*.1);

      line(76*k*.1,46*k*.1,56*k*.1,46*k*.1);

      line(56*k*.1,46*k*.1,56*k*.1,76*k*.1);

      line(56*k*.1,76*k*.1,40*k*.1,76*k*.1);

      line(40*k*.1,76*k*.1,40*k*.1,46*k*.1);

      line(40*k*.1,46*k*.1,16*k*.1,46*k*.1);

      setfillstyle(1,1);//tipo de relleno

      floodfill(40*k*.1,40*k*.1,9);//rellenado

      settextstyle(2,0,1*k*2*.2);//tipo de texto

      outtextxy(65*k*.1,66*k*.1,"Soft.");//texto

 

            delay(100);//retardo del ciclo

 

      }

 

 

otra forma es  usar las siguientes herramientas

 

unsigned int imagesize(int xizq,int y superior,x der,y inferior);  //tamaño de imagen

getimage(int xizq,int y superior,int xderm, int y inferior,void mapa de bits);

putimage(int xizq,int y superior,void mapa de bits,int operador);

COPY_PUT    0

XOR_PUT     1

OR_PUT      2

AND_PUT     3

NOT_PUT     4

 

Moveto(intx,int y);

 

 

Ejemplo:

   maxx = getmaxx();

   x = 0;

   y = getmaxy() / 2;

 

   /* draw the image to be grabbed */

   draw_arrow(x, y);

 

   /* calculate the size of the image */

   size = imagesize(x, y-ARROW_SIZE, x+(4*ARROW_SIZE), y+ARROW_SIZE);

 

   /* allocate memory to hold the image */

   arrow = malloc(size);

 

   /* grab the image */

   getimage(x, y-ARROW_SIZE, x+(4*ARROW_SIZE), y+ARROW_SIZE, arrow);

 

   /* repeat until a key is pressed */

   while (!kbhit())

   {

      /* erase old image */

      putimage(x, y-ARROW_SIZE, arrow, XOR_PUT);

 

      x += ARROW_SIZE;

      if (x >= maxx)

        x = 0;

 

      /* plot new image */

      putimage(x, y-ARROW_SIZE, arrow, XOR_PUT);

   }

 

   /* clean up */

   free(arrow);

   closegraph();

   getch();

   return 0;

 

}

 

void draw_arrow(int x, int y)

{

   /* draw an arrow on the screen */

   moveto(x, y);

   linerel(4*ARROW_SIZE, 0);

   linerel(-2*ARROW_SIZE, -1*ARROW_SIZE);

   linerel(0, 2*ARROW_SIZE);

   linerel(2*ARROW_SIZE, -1*ARROW_SIZE);

}