Graficos en C

Descargar como pdf o txt
Descargar como pdf o txt
Está en la página 1de 9

07/04/2011

Graficos en C

En el modo grfico existe una enorme cantidad de funciones que realizan desde la tarea mas sencilla como es pintar un pxel, hasta la tarea mas compleja como pudiera ser dibujar un carcter por medio de trazos. Para trabajar el modo grfico es necesario incluir la librera graphics.h como hacer uso de la BGI (Borlan Graphics Interphase) Para usar cualquier funcin es necesario colocar el adaptador de video en modo grafico y esto se logra a travs de la funcin initgraph(); y al terminares necesario regresar al modo original a travs de la funcin closegraph(); Para iniciar un programa en ambiente grfico es recomendable correr una subrutina de inicializacin de grficos y deteccin de errores. Algunos ejemplos de las funciones que se pueden encontrar en la librera de grphics.h son: Line(); circle(); arc(); elipse();rectangle(); ottextxy(); putpixel(); Para saber mas de las funciones de la librera de grficos lo pueden buscar en el ndice de turbo c NOTA: Para dar de alta en tu computadora el modo de grficos 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


tonahtiu.com/notas//Graficos_C.htm 1/9

07/04/2011

Graficos en C

#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

TAMAO O RESOLUCION DE LA PANTALLA 640X480 PIXELS


tonahtiu.com/notas//Graficos_C.htm 2/9

07/04/2011

Graficos en C

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, tamao letra); TIPOS DE LETRA (FONT) 0 1 2 3 4 DEFAULT_FONT TRIPLEX_FONT SMALL_FONT SANS_SERIF_FONT 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 ARRIBA 2 TOP_TEXT RELLENADO DE FIGURAS
tonahtiu.com/notas//Graficos_C.htm 3/9

07/04/2011

Graficos en C

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
tonahtiu.com/notas//Graficos_C.htm 4/9

07/04/2011

Graficos en C

int main(void) { int gdriver = DETECT, gmode, errorcode;//variables para detectar modo grafico int x1,x2,y1,y2,x,y; //variables para tamao 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 grficos usamos coordenadas x y y y se mide en pxeles en c standard y dependiendo de la computadora ,x tiene un mximo de 639, y tiene un mximo de 479. El modo para inicializar grficos es :
tonahtiu.com/notas//Graficos_C.htm 5/9

07/04/2011

Graficos en C

Int gdriver=DETECT,gmode; Initgraph(&gdriver,&gmode,direccin de la carpeta bgi de tc); Existen varias funciones estndar con las que podemos trabajar en grficos: 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 rectngulo Putpixel(int x, int y ,int color); //pone un pixel Settextstyle(int tipo de letra, int orientacin, int tamao); Orientacin 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
tonahtiu.com/notas//Graficos_C.htm 6/9

07/04/2011

Graficos en C

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

Y0 X0 Para poder graficar una funcin 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 interseccin entre las lneas es (449,159) esto significa que este es nuestro origen 0 Usando la funcin double evaluafuncion(char [], double); Evaluamos nuestra funcin utilizando un ciclo, en donde se incremente el valor double que le enviamos a nuestra funcin.

double result; a=0.0; Ciclo { a=a+.01; por ejemplo. evaluarfuncion(funcin ,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 bsico para poder graficar una funcin. Existe diferentes formas para poder hacer una animacin. Una de las mas sencillas es hacer un algoritmo de incremento de coordenadas combinado con limpieza de pantalla , dentro de un ciclo.
tonahtiu.com/notas//Graficos_C.htm 7/9

07/04/2011

Graficos en C

for(int k=0;k<50;k++) { cleardevice();//borra pantalla setcolor(LIGHTBLUE);//elije el color para las lneas 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); //tamao 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);
tonahtiu.com/notas//Graficos_C.htm 8/9

07/04/2011

Graficos en C

/* 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); }

tonahtiu.com/notas//Graficos_C.htm

9/9

También podría gustarte