The optimal grid for any number of items

Recently I worked on a feature where I had to generate an image sprite for a number of equally sized images. Even though you can simply put all of these images below each other, I found it a challenge to generate an image sprite that was as closest to a square and with as little white-spacing as possible. What I ended up with is a function that calculates the optimal size of the grid (columns and rows) for any number of items.

An easy solution would be for 25 items: you’ll get an image sprite of 5 columns and 5 rows.

A grid of 25 items with 5 columns and 5 rows

It becomes harder if you look at 19: the only solution without white-spaces is a sheet of 19 columns and 1 row.

A grid of 19 items with 19 columns and 1 row

But if you want the result to be as square as possible you would end up with 5 columns and 4 rows, leaving you with 1 white-space.

A grid of 19 items with 5 columns and 4 rows

I wrote a function that calculates the optimal square-like grid size for any number of items. Additionally you can pass the minimum ratio you want; the function will loosen the threshold of white-spaces every time no grid can be created with a ratio above it.

 

Leave a Reply

Your email address will not be published. Required fields are marked *