Rectangle Packer

2.1.0 · active · verified Fri Apr 17

rectangle-packer is a Python library for efficiently packing a set of 2D rectangles into a minimal bounding box. It utilizes an optimized best-fit heuristic algorithm to achieve high packing density. The current stable version is 2.1.0, and it maintains a moderate release cadence, with updates addressing performance and edge cases, primarily focusing on its core `pack` functionality.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a list of rectangles as (width, height) tuples and use `rpack.pack()` to find their optimal positions within a minimal bounding box. It then prints the calculated (x, y) positions for each rectangle and the overall dimensions of the packed area.

import rpack

# Rectangles are defined as (width, height) tuples
rects = [
    (10, 20),
    (5, 15),
    (12, 12),
    (30, 10),
    (8, 25)
]

# Pack the rectangles, returns a list of (x, y) positions
# (0,0) is top-left, increasing x to the right, increasing y downwards
positions = rpack.pack(rects)

# The positions correspond to the input rectangles order
for i, (x, y) in enumerate(positions):
    print(f"Rectangle {i+1} (w={rects[i][0]}, h={rects[i][1]}): Position ({x}, {y})")

# You can find the enclosing dimensions of the packed layout
width, height = rpack.util.enclosing_size(rects, positions)
print(f"Total enclosing size: Width={width}, Height={height}")

view raw JSON →