Note. I could not fully understand Frederick's answer, so I myself dealt with this problem and came up with something that looks like the same thing. I thought I could explain what I did if it would be helpful.
First, I normalized the aspect ratio of the view to the object. (I assume you do not want to rotate the elements.)
a = (view_width/view_height) / (item_width/item_height)
Now packing a rectangle with a width / height ratio a with squares is equivalent to packing a view with elements. An ideal case would be for our grid (squares now) to completely fill the rectangle, which will give us
a = c/r
where r and c are the numbers of rows and columns:
N = r*c
Multiplication / division of these two equations gives us
N*a = c^2 N/a = r^2 c = sqrt(N*a) r = sqrt(N/a)
If the grid is perfect, r and c will be integers, but if not, you need to try the three options mentioned by Frederick, and save the one where r*c smallest, but even more N
floor(r), ceil(c)ceil(r), floor(c)ceil(r), ceil(c)
source share