Advertisement
Shailrshah

Line Drawing Algorithms

Aug 28th, 2014
350
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.66 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <math.h>
  3. #include <conio.h>
  4. #include <graphics.h>
  5.  
  6. void startGraphics(){
  7.     int gd=DETECT, gm;
  8.     initgraph(&gd, &gm, "C:\\TURBOC3\\BGI");
  9. }
  10.  
  11. void dda(int x1, int y1, int x2, int y2){
  12.         int i, length, absx = abs(x2-x1), absy = abs(y2-y1);
  13.         float dx, dy, x, y;
  14.         absx>absy?(length=absx):(length=absy);
  15.         dx = absx/length; dy = absy/length;
  16.         dx>0?(x=x1+0.5):(x=x1-0.5); dy>0?(y=y1+0.5):(y=y1-0.5);
  17.         putpixel((int)x, (int)y, 2);
  18.         for(i=0; i<length; i++){
  19.         x+=dx; y+=dy;
  20.         putpixel((int)x, (int)y, 2);
  21.         }
  22. }
  23.  
  24. void bres(x1, y1, x2, y2){
  25.     int i, x=x1, y=y1, dx = abs(x2-x1), dy = abs(y2-y1);
  26.         float e = 2 * dy - dx;
  27.         putpixel(x, y, 3);
  28.         for(i=0; i<dx; i++){
  29.         for(; e >=0; e-= 2*dx) y++;
  30.         x++;
  31.         e += 2*dy;
  32.         putpixel(x, y, 3);
  33.         }
  34. }
  35.  
  36. void swap(int *a, int *b){
  37.     int t = *a;
  38.         *a = *b;
  39.         *b = t;
  40. }
  41.  
  42. void gbres(x1, y1, x2, y2){
  43.         int i, x=x1, y=y1, dx = abs(x2-x1), dy = abs(y2-y1), flag = 0, sx, sy;
  44.         float e;
  45.    
  46.         ((x2-x1)>0)?(sx=1):(sx=-1); ((y2-y1)>0)?(sy=1):(sy=-1);
  47.         if(dx < dy){swap(&dx, &dy); flag = 1;}
  48.    
  49.         e = 2 * dy - dx;
  50.         putpixel(x, y, 4);
  51.  
  52.         for(i=0; i<dx; i++){
  53.             for(; e >=0; e -= 2*dx)
  54.                     if(flag) x+=sx;
  55.                     else y+=sy;    
  56.             if(flag) y+=sy;
  57.             else x+=sx;
  58.             e += 2*dy;
  59.             putpixel(x, y, 4);
  60.         }
  61. }
  62.  
  63. void main(){
  64.         char ch;
  65.     startGraphics();
  66.     cleardevice();
  67.  
  68.         ch = getch();
  69.         if(ch=='d') dda(200, 200, 300, 300);
  70.     else if(ch=='b') bres(200, 200, 300, 300);
  71.     else if(ch=='g') gbres(200, 200, 300, 300);
  72.  
  73.  
  74.     getch();
  75.     closegraph();
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement