MxLDevs
MxLDevs

Reputation: 19506

Algorithms for placing images on a screen "nicely"

Note: This is not for a webpage, it is a simple program that holds a set of images and will randomly pick a number of images and display them on the screen. Imagine working with an image editor and manually positioning imported images on the canvas.

I am having difficulty coming up with a way to position a set of arbitrary images on a screen of fixed dimension (it's just a window)

So for example, if I have one image, I would probably just position it in the center of the screen.

          |

If I have two images, I would try to place them in the center of the screen, but then spread them apart horizontally so that they look centered relative to each other and also the screen.

     |          |

But what if one image is larger than the other two? I might have something like

    |-----|

  |         |

Similarly, maybe I have two larger ones and two smaller ones

|-----|   |-----|

  |         |

So that the large one appears "in the back" while the small ones are up front.

It is inevitable that some images will end up covering up parts of other images but the best I can do is try to make it as orderly as possible.

I can quickly grab the dimensions of each image object that is to be drawn, and there is a limit on how many images will be drawn (from 1 to 8 inclusive).

Images can be drawn anywhere on the screen, and if any part of the image is outside of the screen those parts will just be cut off. All images have dimensions smaller than the dimensions of the screen, and are typically no bigger than 1/4 of the entire screen.

What is a good way to approach this problem? Even handling the base cases like having two images (of possibly different sizes) is already pretty confusing.

Upvotes: 2

Views: 631

Answers (2)

Li-aung Yip
Li-aung Yip

Reputation: 12486

You could treat this as the 2D bin packing problem, which will optimise for non-overlapping rectangles in a "compact" way, though aesthetics won't be a consideration.

If you want to roll your own, you could try placing all images on the canvas on a grid, with the centre-to-centre spacing being large enough that no images overlap. Then "squash" the images closer together, left to right and top to bottom, to reduce the amount of whitespace.

Upvotes: 1

Aprillion
Aprillion

Reputation: 22324

html tables of 100% width and height (with disabled overflows) are a good starting point IMO - in the first iteration just order the pictures by size and make 8 templates like:

  1. <tr><td><img></td></tr>
  2. <tr><td><img></td><td><img></td></tr>
  3. 2 rows, first with colspan=2
  4. ...

then find some ugly cases and make special rules for them (like for 3 vertical images make 1 row, ...)

Upvotes: 0

Related Questions