A Go package for packing rectangles into a bin using the MaxRects algorithm.
WARNING: This algorithm prioritizes minimizing wasted space over raw performance. Using rectangles with extremely large dimensions can significantly increase computation time. If you need to pack a large number of rectangles, consider a more efficient solution—such as the Skyline algorithm.
go get github.com/lewisgibson/go-binpack
package main
import (
"github.com/lewisgibson/go-binpack"
)
// Collager is a struct that implements the binpack.Packer interface.
type Collager struct {
Images []image.Image
Locations []image.Point
}
// Len returns the number of images in the Collager.
func (c *Collager) Len() int {
return len(c.Images)
}
// Rectangle returns the dimensions of the image at index n.
func (c *Collager) Rectangle(n int) binpack.Rectangle {
return binpack.Rectangle{
Width: c.Images[n].Bounds().Dx(),
Height: c.Images[n].Bounds().Dy(),
}
}
// Place sets the location of the image at index n.
func (c *Collager) Place(n, x, y int) {
c.Locations[n] = image.Point{x, y}
}
// Create a new Collager.
c := &Collager{
Images: images,
// Locations is a pre-allocated slice of image.Point structs with the same length as images.
Locations: make([]image.Point, len(images)),
}
// Pack the images into a collage.
width, height := binpack.Pack(c)