Wednesday, March 19, 2014

bresenham line drawing algorithm in c



 

General idea how Bresenham Line drawing Algorithm works
Uses only integer calculations

Uses distance between ideal y-coordinate and the upper and lower pixel (assuming gentle slope)


Suppose that the line is gently sloping upwards from left to right.

Start by coloring the left-most pixel.

Then, for the next column (that is, for each x value), we have to figure out whether we color the same y or y+1.

How do we decide?
When going from one column to the next, add an error value. If the error value is more than 0.5, we should color y+1 and reset the error value. Otherwise, color y and accumulate the error value.

However, it seems like we’re still using floating point
Solution, multiply both sides by 2 so that we use integer comparisons instead.

Algorithm
1.Input the two line endpoints and store left endpoint as (x0,y0)
2.Pre-calculate the values dx, dy, 2dy and 2dy - 2dx
3.Color pixel (x0,y0)
4.Let p0 = 2dy – dx
5.At each xk along the line, starting with k=0:




If pk<0, then the next point to plot is (xk+1 ,yk),
and pk+1= pk + 2dy

Otherwise, the next point to plot is (xk+1 , yk+`),
and pk+1= pk + 2dy – 2dx
6.Repeat Step-4 dx times

(Note pk+1 = pk+1)

Switch Point 0 and Point 1 if necessary
If negative slope, reflect
If steep slope, flip y and x










#include<stdio.h>
#include <graphics.h>
#include <conio.h>
#include<math.h>
void main()
{
   int gdriver = DETECT, gmode;
   int x1,y1,x2,y2;
   float dx,dy,y,x,pk,pk1;

   clrscr();
   initgraph(&gdriver,&gmode,"c:/tc/bgi");
   printf("\nEnter first point(x1,y1)=");
   scanf("%d%d",&x1,&y1);
   printf("\nEnter second point(x2,y2)=");
   scanf("%d%d",&x2,&y2);
   dx=x2-x1;
   dy=y2-y1;
   pk=2*dy-dx;
   for(x=x1;x<x2;x++)
   {
    putpixel(x,y,2);
    if(pk<0)
    {
        pk=pk+2*dy;
    }
    else
    {
        y=y+1;
        pk=pk+2*dy-2*dx;
    }
    }

  getch();
}



No comments:

Post a Comment