Primary use: Given a set of rectangles with fixed orientations, find a bounding box of minimum area that contains them all with no overlap.
This project is inspired by Matt Perdeck's blog post Fast Optimizing Rectangle Packing Algorithm for Building CSS Sprites.
- The latest documentation is available on Read the Docs.
- The source code is available on GitHub.
Install latest version from PyPI:
$ python3 -m pip install rectangle-packer
Or clone the repository and install with:
$ python3 setup.py install
# Import the module
>>> import rpack
# Create a bunch of rectangles (width, height)
>>> sizes = [(58, 206), (231, 176), (35, 113), (46, 109)]
# Pack
>>> positions = rpack.pack(sizes)
# The result will be a list of (x, y) positions:
>>> positions
[(0, 0), (58, 0), (289, 0), (289, 113)]
The output positions are the lower left corner coordinates of each rectangle in the input.
These positions will yield a packing with no overlaps and enclosing area as small as possible (best effort).
Note
- You must use positive integers as rectangle width and height.
- The module name is rpack which is an abbreviation of the package name at PyPI (rectangle-packer).
- The computational time required by :py:func:`rpack.pack` increases by the number and size of input rectangles. If this becomes a problem, you might need to implement your own divide-and-conquer algorithm.
Example A:
Example B:
Example C: Sometimes the input rectangles simply cannot be packed in a good way. Here is an example of low packing density:
Example D: The image below is contributed by Paul Brodersen, and illustrates a solution to a problem discussed at stackoverflow.