Given a set of arbitrarily sized images and a container with fixed dimensions, fit as many of the images within the container as you can, without leaving any big gaps in between images. How would you do it?
Well, I had a go, and this is a brief overview of how it works.
Obviously, it wasn’t possible to simply line the images up as a grid, because they all have varying (and unpredictable) widths and heights. Considering this, I only saw one logical way of doing it… progressively!
Place an image — determine the remaining space and use it to place the next image, and so on. Placing the first image is easy; just stick it up in the top left corner and go from there!
A single placement will open up, potentially, three new positions. Out of them, the top-most one could be used for next placement, or the left-most, whichever you fancy.
I chose to track the availability of pixels using a basic two-dimensional array:
// Nine occupied pixels: [ [1,1,1,0,0,0,0,0,0,0], [1,1,1,0,0,0,0,0,0,0], [1,1,1,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0] ];
The width given to any image upon placement is defined by the amount of pixels free to the right of that image and the height is calculated similarly. There’s a configurable maximum width and height so that the first image doesn’t take up the entire space. Eventually, there is no space left, and the procedure halts.
You can find the code at Github, under “PhotoWall”.
I’ve also put a pretty boring demo online, and yes, I know it’s a bit messed up at the bottom edge — like everything, it’s a work in progress :).