Bresenham's line drawing algorithm in Graphics

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

void Bresenham(int,int,int,int);

int x1,y1,x2,y2;
void main()
{
  int gd = DETECT,gm;
  initgraph(&gd,&gm,"C:\\TC\\BGI");

  printf("Enter x1, y1, x2, y2: ");
  scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
  Bresenham(x1,y1,x2,y2);
  getch();
  closegraph();
}

void Bresenham (int x1,int y1,int x2,int y2)
{
  int x,y,dx,dy,pk,k,xEnd;
  dx=abs(x2-x1);
  dy=abs(y2-y1);
  
  if(x1<x2)
  {
    x = x1;
    y = y1;
    xEnd = x2;
  }
  else
  {
    x = x2;
    y = y2;
    xEnd = x1;
  }
  
  putpixel (x,y,1);
  pk=2*dy-dx;
  
  while (x<=xEnd)
  {
    if(pk<0)
    {
      x=x+1;
      y=y;
      pk=pk+2*dy;
    }
    else
    {
      x=x+1;
      y=y+1;
      pk = pk+2*dy-2*dx;
    }
  
    putpixel (x,y,1);
  }
}


OUTPUT:

No comments:

Post a Comment