Advertisement
Riz1Ahmed

Bresenham line Algorithm

Sep 11th, 2020
993
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.26 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<graphics.h>
  3. int abs(int n) {return n<0? -n:n;}
  4. int swap(int &x,int &y){ x^=y^=x^=y;}
  5. int max(int x,int y){return x>y ? x:y;}
  6.  
  7. void BresenhamLineAlgo(int x1,int y1, int x2,int y2){
  8.     //abs(x1-x2) is less abs(y1-y2), then apply
  9.     int m=abs(x1-x2) > abs(y1-y2);
  10.     if (m==false) swap(x1,y1), swap(x2,y2);
  11.  
  12.     int dX=x2-x1;
  13.     int dY=y2-y1;
  14.     int twodlY=2*dY;
  15.     int _2dY_2dX=2*dY-2*dX;
  16.     int X=x1, Y=y1, k=0,Pk;
  17.  
  18.     while(k<abs(dX)){
  19.         printf("k=%2d, Pk=%3d xy(%2d,%2d)\n",k, Pk, X,Y);
  20.         if (m==true) putpixel (X,Y,YELLOW);
  21.         else putpixel (Y,X,YELLOW);
  22.         delay(10);//So that we can see how draw line
  23.  
  24.         if (k==0)       Pk=2*dY-dX;
  25.         else if (Pk>=0) Pk=Pk+_2dY_2dX;
  26.         else if (Pk<0)  Pk=Pk+twodlY;
  27.  
  28.         if (Pk>=0)     X++,Y++;
  29.         else if (Pk<0) X++;
  30.  
  31.         k++;
  32.     }
  33. }
  34.  
  35. int main(){
  36.     int gd = DETECT, gm;
  37.     initgraph (&gd, &gm, "");//Initialize graphics function
  38.     puts("***Bresenham Line Algorithm***\n");
  39.  
  40.     int x1, y1,x2,y2;
  41.     while(1){
  42.         printf("Enter x1,x1 (Ex:20 10): ");
  43.         scanf("%d %d", &x1, &y1);
  44.         printf("Enter x2,x2 (Ex:30 18): ");
  45.         scanf("%d %d", &x2, &y2);
  46.         BresenhamLineAlgo(x1,y1,x2,y2);
  47.     }
  48.     return 0;
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement