Program in Python graphics.py and C++ graphics library
Python
#Bresenham's Line Drawing
from graphics import *
import time
def BresenhamLine(x1,y1,x2,y2):
dx = abs(x2 - x1)
dy = abs(y2 - y1)
slope = dy/float(dx)
x, y = x1, y1
# creating the window
win = GraphWin('Brasenham Line', 600, 480)
# checking the slope if slope > 1
# then interchange the role of x and y
if slope > 1:
dx, dy = dy, dx
x, y = y, x
x1, y1 = y1, x1
x2, y2 = y2, x2
# initialization of the inital disision parameter
p = 2 * dy - dx
PutPixle(win, x, y)
for k in range(2, dx):
if p > 0:
y = y + 1 if y < y2 else y - 1
p = p + 2*(dy - dx)
else:
p = p + 2*dy
x = x + 1 if x < x2 else x - 1
# delay for 0.01 secs
time.sleep(0.01)
print(x,y)
PutPixle(win, x, y)
win.getMouse()
win.close()
def PutPixle(win, x, y):
""" Plot A Pixle In The Windows At Point (x, y) """
pt = Point(x,y)
pt.draw(win)
def main():
x1 = int(input("Enter Start X: "))
y1 = int(input("Enter Start Y: "))
x2 = int(input("Enter End X: "))
y2 = int(input("Enter End Y: "))
BresenhamLine(x1, y1, x2, y2)
if __name__ == "__main__":
main()
C++
#include <graphics.h>
#include <iostream>
#include <conio.h>
#include <math.h>
using namespace std;
void bresenham(int x0, int y0, int xEnd, int yEnd)
{
int dx = fabs(xEnd - x0), dy = fabs(yEnd - y0);
int p = 2 * dy - dx;
int twoDy = 2 * dy, twoDyMinusDx = 2 * (dy - dx);
int x, y; /* Determine which endpoint to use as start position. */
if (x0 > xEnd)
{
x = xEnd;
y = yEnd;
xEnd = x0;
}
else
{
x = x0;
y = y0;
}
putpixel(x, y, WHITE);
cout <<"k pk x y \n";
cout << -1 << " " << p << " " << x << " " << y << "\n";
int cnt = 0;
while (x < xEnd)
{
x++;
if (p < 0)
p += twoDy;
else
{
y++;
p += twoDyMinusDx;
}
putpixel(x, y, WHITE);
cout <<cnt++ <<" " <<p<<" " << x << " " << y << "\n";
}
}
int main()
{
int gd = DETECT, gm;
initgraph(&gd, &gm, "");
int x0, y0, xend, yend;
cout << "Enter x0, y0 :";
cin >> x0 >> y0;
cout << "Enter xend, yend :";
cin >> xend >> yend;
bresenham(x0, y0, xend, yend);
getch();
closegraph();
return 0;
}