bresenham_line.py

Created by tlake

Created on August 21, 2023

2.21 KB

Draws a line using the Bresenham algorithm


from math import *
from kandinsky import *
def draw_line(x1, y1, x2, y2, c=(0,0,0)):
    
    # Calculate line deltas
    dx = x2 - x1
    dy = y2 - y1
    
    # Create a positive copy of deltas (makes iterating easier)
    dx1 = abs(dx)
    dy1 = abs(dy)
    
    # Calculate error intervals for both axis
    px = 2 * dy1 - dx1
    py = 2 * dx1 - dy1
    
    # The line is X-axis dominant
    if dy1 <= dx1:
        
        # Line is drawn left to right
        if (dx >= 0):
            x = x1; y = y1; xe = x2
        else:
        # Line is drawn right to left (swap ends)
            x = x2; y = y2; xe = x1
        
        set_pixel(int(x), int(y), c); # Draw first pixel
        
        # Rasterize the line
        for i in range(0,xe):
            x = x + 1
            
            # Deal with octants...
            if (px < 0):
                px = px + 2 * dy1
            else: 
                if ((dx < 0 and dy < 0) or (dx > 0 and dy > 0)):
                    y = y + 1
                else: 
                    y = y - 1
                
                px = px + 2 * (dy1 - dx1)
            
            
            # Draw pixel from line span at
            # currently rasterized position
            set_pixel(int(x), int(y), c)
        
        
    else:  # The line is Y-axis dominant
        
        # Line is drawn bottom to top
        if (dy >= 0):
            x = x1; y = y1; ye = y2
        else:
        # Line is drawn top to bottom
            x = x2; y = y2; ye = y1
        
        
        set_pixel(int(x), int(y), c) # Draw first pixel
        
        # Rasterize the line
        for y in range(0,ye):
            y = y + 1
            
            # Deal with octants...
            if (py <= 0):
                py = py + 2 * dx1
            else: 
                if ((dx < 0 and dy<0) or (dx > 0 and dy > 0)):
                    x = x + 1
                else:
                    x = x - 1
                
                py = py + 2 * (dx1 - dy1)
            
            
            # Draw pixel from line span at
            # currently rasterized position
            set_pixel(int(x), int(y), c)
 
#
def line():
  fill_rect(0,0,350,240,(0,0,0))
  draw_line(0,0,350,240,(0,255,0))

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.