The Bresenham algorithm is an incremental scan conversion algorithm.
The big advantage of this algorithm is that, it uses only integer calculations. Moving across the x axis in unit intervals and at each step choose between two different y coordinates.
For example, from below figure, from position (2, 3) you need to choose between (3, 3) and (3, 4). You would like the point that is closer to the original line.
![]() |
Image source: Tutorialspoint |
We can draw various types of lines using Bresenham's Line Algorithm such as:
1. SOLID LINE
2. DOTTED LINE
3. DASHED LINE
4. THICK LINE
Below is a code to draw a Dotted Line using Bresenham's Line Algorithm.
Code:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Title: Bresenham's Line Algorithm (DOTTED LINE) | |
Description: An algorithm to draw a Dotted Line using Bresenham's Line Drawing Algorithm | |
Author: Saideep Dicholkar | |
*/ | |
#include<stdio.h> | |
#include<graphics.h> | |
#include<math.h> | |
void main() | |
{ | |
int gd=DETECT,gm,x,y,x1,y1,x2,y2,dx,dy,i,e; | |
float xinc,yinc; | |
initgraph(&gd,&gm,""); | |
cleardevice(); | |
printf("Enter x1,y1,x2,y2:\n"); | |
scanf("%d%d%d%d",&x1,&y1,&x2,&y2); | |
dx=x2-x1; | |
dy=y2-y1; | |
if(x1<x2) | |
xinc=1; | |
else | |
xinc=-1; | |
if(y1<y2) | |
yinc=1; | |
else | |
yinc=-1; | |
x=x1; | |
y=y1; | |
if(dx>=dy) | |
{ | |
e=(2*dy)-dx; | |
while(x!=x2) | |
{ | |
if(e<0) | |
e=e+(2*dy); | |
else | |
{ | |
e=e+(2*(dy-dx)); | |
y=y+yinc; | |
y=y+yinc; | |
} | |
x=x+xinc; | |
x=x+xinc; | |
putpixel(x,y,WHITE); | |
} | |
} | |
else | |
{ | |
e=(2*dx)-dy; | |
while(y!=y2) | |
{ | |
if(e<0) | |
e=e+(2*dx); | |
else | |
{ | |
e=e+(2*(dx-dy)); | |
x=x+xinc; | |
x=x+xinc; | |
} | |
y=y+yinc; | |
y=y+yinc; | |
putpixel(x,y,WHITE); | |
} | |
} | |
getch(); | |
closegraph(); | |
restorecrtmode(); | |
} |
Output:
![]() |
Dotted Line |
Comments
Post a Comment