Bresenham Line Drawing Algorithm in C and C++
Here, you will know about Bresenham Line Drawing Algorithm and get the example code of Bresenham Line Drawing Algorithm in C and C++. In the following examples, we will be using the turbo c++ compiler to run graphics program.
Bresenham line drawing algorithm is an efficient way to plot a line. It’s an incremental algorithm that calculates the next pixel to draw depending on the current one.
The Bresenham Line Drawing Algorithm is very fast, accurate and efficient in computer graphics.
Bresenham Line Drawing Algorithm
Step 1: get input (x1, y1) and (x2, y2)
Step 2: search dx = x2 – x1 and dy = y2 – y1
Step 3: x=x1 and y=y1
Step 4: p=2*dy-dx
Step 5:
while(x<x2)
{
if(p>=0)
{
putpixel(x,y,7);
y=y+1;
p=p+2*dy-2*dx;
}
else
{
putpixel(x,y,7);
p=p+2*dy;
}
x=x+1;
}
Program for Bresenham Line Drawing Algorithm in C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | // Bresenham's Line Drawing Algorithm in C #include<stdio.h> #include<graphics.h> int main() { int gdriver=DETECT,gmode,x1,y1,x2,y2; int dx,dy,p,x,y; initgraph(&gdriver,&gmode,"c:\\turboc3\\bgi"); printf("\n\n Bresenham's Algorithm Line Program "); printf("\nEnter first point coordinates : "); scanf("%d%d", &x1, &y1); printf("\nEnter second point coordinates : "); scanf("%d%d",&x2,&y2); dx=x2-x1; dy=y2-y1; x=x1; y=y1; p=2*dy-dx; while(x<x2) { if(p>=0) { putpixel(x,y,15); y=y+1; p=p+2*dy-2*dx; } else { putpixel(x,y,15); p=p+2*dy; } x=x+1; } getch(); return 0; } |
Program for Bresenham Line Drawing Algorithm in C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | //Bresenham's Line Drawing Algorithm in C++ #include<iostream.h> #include<graphics.h> int main() { int gdriver=DETECT,gmode,x1,y1,x2,y2; int dx,dy,p,x,y; initgraph(&gdriver,&gmode,"c:\\turboc3\\bgi"); cout<<"\n\n Bresenham's Algorithm Line Program "; cout<<"\nEnter first point coordinates : "; cin>>x1>>y1; cout<<"\nEnter second point coordinates : "; cin>>x2>>y2; dx=x2-x1; dy=y2-y1; x=x1; y=y1; p=2*dy-dx; while(x<x2) { if(p>=0) { putpixel(x,y,15); y=y+1; p=p+2*dy-2*dx; } else { putpixel(x,y,15); p=p+2*dy; } x=x+1; } getch(); return 0; } |
Output: