Sunday 31 March 2013

Implementation Of BLA Line Drawing Algorithm

Here is the source code that makes use of the traditional DOS mode graphics to implement the Bresenham line drawing algorithm for the lines with slope |m| < 1.

Bresenham Line Drawing Algorithm for |m| < 1


Algorithm


1) Input two points (x1, y1) & (x2, y2).
2) Determine the differences dx = x2 - x1 and dy = y2 - y1.
3) Calculate the initial decision parameter P0 = 2dy - dx.
4) For each xk along the line starting at k = 0,
   if Pk < 0,
      a) put a pixel at (xk + 1, yk)
      b) Pk+1 = Pk + 2dy
   else
      a) put a pixel at (xk + 1, yk + 1)
      b) Pk+1 = Pk + 2dy - 2dx.
5) Repeat step 4 for dx time.
6) End

Source Code


#include <stdio.h>
#include <conio.h>
#include <graphics.h>
#include <math.h>

int main()
{
 int gd = DETECT, gm;
 int x1, y1, x2, y2, dx, dy;
 int x, y, i, p0, pk;
 printf("Enter x1, y1: ");
 scanf("%d %d", &x1, &y1);
 printf("Enter x2, y2: ");
 scanf("%d %d", &x2, &y2);

 dx = x2 - x1;
 dy = y2 - y1;

 x = x1;
 y = y1;
 p0 = ( 2 * dy - dx);
 initgraph(&gd, &gm, "C:\\TurboC3\\BGI");
 pk = p0;
 for (i = 0; i < abs(dx); i++)
 {
  if (pk < 0)
  {
   putpixel(x, y, WHITE);   
   pk += (2 * dy);
  }
  else
  {
   putpixel(x, y, WHITE);
   pk += (2 * dy - 2 * dx);
  }

  (x1 < x2)?x++:x--;
  (y1 < y2)?y++:y--;
  
  delay(50);
 }
  
 getch();
 closegraph();
 return 0;
}


Make sure to provide an appropriate path for graphics library.