Reputation: 1
I want to draw an image gallery and I am having some problems in the algorithm to be executed.
Basically I have an area of 1000x700 and I want to fill this area maximum previews. These images are located in a list of images, all images must be the same size. This gallery is only a preview is in this area that the size does not match the original size of each image.
Can anyone give me an overview of a pseudo-algorithm so I can build it?
Thank you!
Upvotes: 0
Views: 120
Reputation: 10579
Your problem can be reduced to the problem of finding the number of rows and columns for your tabular layout of images such that:
columns * (rows-1) < k <= columns * rows
Constraint 1 is roughly:
cols / rows = 1000/700
Constraint 2 is roughly:
cols * rows = k (where k is the number of images to be displayed)
Solving for rows and cols in terms of k gives you:
rows = sqrt(700*k/1000)
cols = sqrt(1000*k/700)
The tricky part is that rows and cols need to be rounded to integers, while at the same time ensuring that rows * cols >= k (i.e. you have enough cells in your tabular layout to hold each image).
As a rule of thumb, I would try rounding your smaller dimension (rows) up, and your bigger dimension (cols) down.
rows = ceiling(sqrt(700*k/1000))
cols = floor(sqrt(1000*k/700))
If you find that this doesn't always work, then you might need something like
if (rows * cols < k) rows = rows + 1;
Once you know the number of rows and columns of your layout, and decide on the size of the margin between images, then you can easily calculate the required dimensions of the thumbnails.
Upvotes: 1
Reputation: 2217
This is a search algorithm.
Start by writing a function that tries to lay out thumbnails of a given size, within the area. It returns true if all the thumbnails will fit, otherwise it returns false.
Take the shortest side of the area (700). Try a thumbnail of that size. Using your function, see it it fits.
If it doesn't fit, try the next possible size (700/2).
If that doesn't fit, try the next one (700/3) etc.
That's a reasonable algorithm. You can make it even better by noticing that there are some other possible sizes that might work. (1000 (won't work, but makes the sequence easy), 700, 1000/2, 700/2, 1000/3, 700/3, 1000/4...
Try converting that to code, and come back with what you've done if can't get it to work.
Upvotes: 0