Masonry-like picture grid
I have been over-thinking this complex and I am sure there is an easy answer or another avenue I can approach to find the solution.
What I am trying to accomplish is a random grid of images. I have an array of images that I want to line up in a flush grid. What I mean by this is that I want the grid to not have any gaps in it. Here are some example images:
- Container/cell must be in a ratio that the image can fit without skewing
- The grid must be flush. It cannot have any gaps including the last row.
The problem I am having is I cannot come up or put into words a formula that can create the table maxtrix I am trying to accomplish. Masonary is 99.9% what I am looking for except the grid does not take into account the image size nor does it end flush. So that 1% is why I am not considering using it.
Any help or pointers will be appreciated.
Your example images are alinged in rows. Furthermore, you didn't wirte anything about a fixed total size, so I assume that the aspect ratio of the whole layout can be chosen at will. In that case, you could try something along these lines:
- Line up all the images in a single row, by fixing the height and choosing the width in such a way that you can preserve the aspect ratio.
- Split that single row into multiple rows. This is where you can play with a number of heuristics, to tune the final result to your preferences. But any solution would satisfy the requirements you stated.
- Scale each row in such a way that they all have the same width, then stack them.
Obvious this is only a rough outline. The really hard part will be how to distribute the images onto the different rows. One goal might be combining images of similar aspect ratio, in such a way that the final images will have similar sizes. You could compute for each ratio the preferred image height which would lead to a desired image area, and then combine images with similar height requirements until the width resulting from scaling to a common height matches the width you desire for your final rows. But other aspects will play a role as well, e.g. making rows of similar width, and stuff like that.
You might find suggestions for objectives in other answers and comments, and toy with them until you find one you like.