How large rectangles fit on canvas

233 Views Asked by At

I have images whose side ratios are known, and the number of images is known. I have canvas whose measurements are known. I need to know what's the optimal length of images sides so that all my images would fit on canvas and maximum area is used. All images are of the same size. And images should be placed correctly for viewing. (not on a side that would make image horizont be in vertical angle.)

I put the question under discrete-mathematics, let me know if it's in a wrong place.

Thanks. :)

2

There are 2 best solutions below

0
On BEST ANSWER

This link had (Almost) the answer: https://stackoverflow.com/questions/10643129/split-screen-based-on-number-of-items-and-screen-ratio

// Set this to the desired x-to-y ratio. const preferred_ratio = 1.2;

function calc_cols_rows(In: screen, In: num_items, Out: num_rows, Out: num_cols) { desired_aspect = (screen.width / screen.height) / preferred_ratio;

// Calculate the number of rows that is closest to the desired aspect:

num_rows = round(sqrt(num_items / desired_aspect));

// Calculate the required number of columns:

num_cols = ceil(num_items / num_rows); }

4
On

Let's say you want to resize an image of size $l_1 \times w_1$ in a canvas sized $L \times W$. Then your scale factor to maximize the resized image allows one of its dimensions to reach the canvas dimension.

Thus we find a scale factor $s=Min(L/l_1,W/w_1)$ and a resized image of dimensions $l_2 \times w_2 = l_1 \cdot s \times w_1 \cdot s$.

  • If the length to width ratio of the image is larger than the canvas, then the length dimension will be filled $l_2 = l_1 \cdot s = l_1 \cdot L/l_1 = L$.
  • Otherwise, the width dimension will be filled $w_2 = w_1 \cdot s = w_1 \cdot W/w_1 = W$.

For multiple images aligned in a M*N rectangular fashion, swap $l_1$ and $w_1$ for $M \cdot l_1$ and $N \cdot w_1$. For any other adjustment, find the dimensions of the whole merged group and apply the same rules as if it was a single (bigger) image.