Simple GUI Notepad Using Ruby

GUI Notepad Using Ruby Code require 'tk' class Notepad def saveFile file = File.open("note", "w") ...

Thursday, April 23, 2015

Bresenham's Line Drawing Python Implementation

Bresenham's line drawing algorithm for drawing a line in a computer screen by using integer arithmetic operations only. It is more efficient that the older DDA Line drawing algorithm that uses floating-point arithmetic and rounding operations although it can be optimised to perform only integer operations still pixle selection using Besenham's gives better result than DDA.

Python3 implementation of the algorithm is given below using graphics module by John M.Zelle


from graphics import *
import time

def BresenhamLine(x1,y1,x2,y2):
    """ Bresenham Line Drawing Algorithm For All Kind Of Slopes Of Line """
   
    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)
        PutPixle(win, x, y)

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()


Output For (50,60) to (300,400)