Vertical line using Bresenham Line Algorithm printing a point, not a line

517 views Asked by At

I am trying to do vertical lines using Bresenham's Line Algorithm. But when I put coordinate for a vertical line, it is printing a point only, not showing a vertical line.

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

     int main( )
     {
         int x1,y1,x2,y2,dx,dy,ds,dt,d,x,y;
         /* request auto detection */
         int gdriver = DETECT, gmode, errorcode;
      
        /* initialize graphics and local variables */
         initgraph(&gdriver, &gmode, "c:\\tc\\bgi");

         x1=200;
         x2=200;
         y1=200;
         y2=300;

         x=x1;
         y=y1;
         dx=x2-x1;
         dy=y2-y1;
         dt=2*(dy-dx);
         ds=2*dy;
         d=2*dy-dx;

         printf("Using Bresenham's Line Algorithm");
         putpixel(x,y,7);

         while(x<=x2)
            {
            x=x+1;
            if(d<0)
                 d=d+ds;
            else
                 {
                y=y+1;
                d=d+dt;
                 }
            putpixel(x,y,7);
            }

           getch();
       closegraph();
       return 0;
}

When I put x1=200 x2=200 it gives me an error. Why am I getting the error? But in normal line function, I am getting the right result, but when putting in Bresenham, I am getting the wrong result.

1

There are 1 answers

0
Goswin von Brederlow On

Bresenham like you implemented can only draw lines with a slope between 0° and 45° since every loop increases x by one and conditionally increases y by one.

What you have to do is first check if the line goes left to right. If not you have to switch the endpoints.

Next if the line slopes down instead of up you have to decrement y instead of incrementing it. You can store 1 or -1 in a temp variable depending on whether the lines slopes up or down and add that to y when needed.

And if the change in y is greater than the change in x you have to swap the coordinates around in the algorithm incrementing y every loop and x conditionally. For this you actually have to duplicate the whole loop.