Rasterization Using Bresenham Algorithm and Scanline Algorithm

Published: (May 18, 2026 at 12:49 AM EDT)
2 min read
Source: Dev.to

Source: Dev.to

Overview

Bresenham’s algorithm is the fastest method for drawing straight lines on a pixel grid using only integer arithmetic.
The Scanline algorithm is commonly used to fill the interior of polygons by drawing horizontal scanlines between edges.

In this project I implemented basic rasterization techniques in Python with Pygame by applying the Bresenham algorithm for line drawing and the Scanline algorithm for polygon filling. The goal was to manually draw geometric shapes using lines and fill their interiors with color, gaining insight into how rendering and polygon filling work internally in graphics systems.

Development Process

Bresenham line drawing

# draw line
def DrawLine(surface, x1, y1, x2, y2, color):
    dx = abs(x2 - x1)
    dy = abs(y2 - y1)

    stepX = 1 if x1  -dy:
            error -= dy
            x += stepX

        if e2  xb:
            xa, xb = xb, xa
        # draw horizontal line
        DrawLine(surface, xa, y, xb, y, color)

        # optional visualization delay
        pygame.display.update()
        pygame.time.delay(15)

The algorithm first sorts the triangle vertices by their y‑coordinates. It then interpolates the x‑coordinates along the two edges that form the left and right boundaries of each scanline. Horizontal lines are drawn between the left (xa) and right (xb) positions for every scanline, effectively filling the triangle.

Rectangle filling using two triangles

# fill rectangle using 2 triangles!
def FillRectangle(surface, vertices, color):
    # vertices order: 0 = top‑left, 1 = top‑right,
    # 2 = bottom‑right, 3 = bottom‑left
    triangle1 = [vertices[0], vertices[1], vertices[2]]
    triangle2 = [vertices[0], vertices[2], vertices[3]]

    FillTriangle(surface, triangle1, color)
    FillTriangle(surface, triangle2, color)

A rectangle is split into two triangles, each filled with the FillTriangle routine, avoiding the need for a separate rectangle‑filling implementation.

Result

The project demonstrates custom line drawing and polygon filling without relying on built‑in Pygame primitives. The rectangle‑filling function reuses the triangle filler, illustrating code reuse and efficiency.

  • Preview GIF – (insert GIF here)
  • Full video – (link to video)
  • YouTube video – (link to YouTube)
  • GitHub repository – (link to repository)
0 views
Back to Blog

Related posts

Read more »

Click (2016)

Article Click 2016https://clickclickclick.click/ Discussion Hacker News threadhttps://news.ycombinator.com/item?id=48187054 – 194 points, 41 comments...