Search Here

Python program to draw Straight Line using Bresenham algorithm

# Line using Bresenham Algorithm

import pygame
from pygame import gfxdraw
import time

# pygame.init()
screen = pygame.display.set_mode((400,400))
screen.fill((255,255,255))
# pygame.display.flip()
black=(0,0,0)

def ROUND(n):
    return int(n+0.5)

def BRESENHAM_LINE(x1,y1,x2,y2):
    dx = abs(x1-x2)
    dy = abs(y1-y2)

    p = 2*dy - dx
    x = x1
    y = y1
    gfxdraw.pixel(screen,ROUND(x),ROUND(y),black)   
    
    for k in range(0,dx):
        if p<0:
            if x<x2:
                x = x+1
            else:
                x = x-1
            p = p + 2*dy
        else:
            if x<x2:
                x = x+1
            else:
                x = x-1
            
            if y<y2:
                y = y+1
            else:
                y = y-1
                
            p = p + 2*(dy-dx)
        gfxdraw.pixel(screen,ROUND(x),ROUND(y),black)
        
    pygame.display.flip()
    time.sleep(5)
    
BRESENHAM_LINE(50,60,200,300)

No comments:

Post a Comment