Bresenham’s Line Drawing Algorithm

Write a program to implement Bresanham’s line drawing algorithm.


#include<stdio.h>
#include<graphics.h>
#include<conio.h>
void Bline(int,int,int,int);
void main()
{
	int x1,y1,x2,y2;
	int gd=DETECT,gm;
	initgraph(&gd,&gm,"c:\\tc\\bgi");
	printf("\n Enter the coordinates: ");
	scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
	Bline(x1,y1,x2,y2);
	getch();
	closegraph();
}
void Bline(int x1,int y1,int x2,int y2)
{
	int dx,dy,tdy,tdydx,x,y,xend,flag=0,yend;
	long p;
	dy=abs(y1-y2);
	dx=abs(x1-x2);
	p=2*dy-dx;
	tdy=2*dy;
	tdydx=2*(dy-dx);
	if(x1>x2)
	{
		x=x2;
		y=y2;
		xend=x1;
		if(y2>y1)
			flag=1;
	}
	else
	{
		x=x1;
		y=y1;
		xend=x2;
		if(y1>y2)
			flag=1;
	}
	putpixel(x,y,WHITE);
	if(x1==x2)
	{
		if(y1<y2)
		{
			y=y1;
			yend=y2;
		}
		else
		{
			y=y2;
			yend=y1;
		}
		while(y<yend)
		{
			y++;
			putpixel(x,y,WHITE);
		}
	}
	else
	{
		while(x<xend)
		{
			x++;
			if(p<0)
				p+=tdy;
			else
			{
				if(flag==1)
					y--;
				else
					y++;
				p+=tdydx;
			}
			putpixel(x,y,WHITE);
		}
	}
	putpixel(0,0,WHITE);
	putpixel(639,479,WHITE);
}

Output
1

Leave a Reply

Your email address will not be published. Required fields are marked *