Bresenham's algorithm finds the closest integer coordinates to the actual line, using only integer math. Assuming that the slope is positive and less than 1, moving 1 step in the x direction, y either stays the same, or increases by 1. A decision function is required to resolve this choice.



If the current point is (xi, yi), the next oint can be either (xi+1,yi) or (xi+1,yi+1) . The actual position on the line is (x+1, m(x+1)+c) . Calculating the distance between the true point, and the two alternative pixel positions available gives:

d1 = y - yi

     = m * (x+1)+b-yi

d2 = yi + 1 - y

     = yi + 1 – m ( xi + 1 ) – b 

#include<graphics.h>
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
/* ************************************************ */
/* C Program for Drowing a Line on screen */
/* Using Bresenham's Line-Drawing Algorithm */
/* Written By: Ritesh Kumar Jain */
/* ************************************************ */

void initialize_graph(void)
{

     /* select a driver and mode that supports */
     /* set also tha background color */
     /* for example: int driver=EGA , gmode=EGAHI */

     int gdriver= DETECT, gmode;

     initgraph(&gdriver, &gmode,"\\tc\BGI");
     cleardevice();
     setbkcolor(BLUE);
}

void draw_pixel(int w, int q)
{


     /* This function draws a pixel */
     /* recorrelate to start from the lower left corner */

     putpixel(w,480-q,RED);
}

void LineBres(void)
{

      /* this functions drow a line using Bresenham Algorithm */
      /* the slop is m where 0<m<1 */

      int xa,ya,xb,yb,dx,dy,p,twoDy,twoDyDx,x,y,xEnd;

      /* input(xa,ya) and (xb,yb) */

      printf(" ********* WELCOME********* \n\n ");
      printf(" Enter start and end points \n");
      printf("xa= "); scanf("%d",&xa);
      printf("\nya= "); scanf("%d",&ya);
      printf("\nxb= "); scanf("%d",&xb);
      printf("\nyb= "); scanf("%d",&yb);

      dx = abs(xa-xb);
      dy = abs(ya-yb);
      p = 2 * dy - dx ;
      twoDy = 2 * dy;
      twoDyDx = 2 * (dy-dx);

      /* Detemine which point to use as a start, which as end */

      if(xa > xb)
      {
            x=xb;
            y=yb;
            xEnd = xa;
      }

      else
      {
           x=xa;
           y=ya;
           xEnd=xb;
      }

      cleardevice();
      draw_pixel(x,y);

      while(x<xEnd)
      {
            x++;
            if(p<0)
                   p += twoDy;
            else
            {
                   y++;
                   p += twoDyDx;
             }
             draw_pixel(x,y);
       }
  /* End of LineBres */
}

void close_graph(void)
{
       /* clean up */

       closegraph();
}

void main(void) /* Start of main peogram */
{
          initialize_graph();
          LineBres();
          getch();
          close_graph();
/* end of main */
}

0 comments