optimized grid for rectangular items

Note: I couldn't quite understand Frédéric's answer, so I worked the problem out myself and came up with what appears to be the same solution. I figured I might as well explain what I did in case it is helpful.

First I normalized the aspect ratio of the view to that of the items. (I'm assuming you don't want to rotate the items.)

a = (view_width/view_height) / (item_width/item_height)

Now packing a rectangle of width/height ratio a with squares is equivalent to packing the view with items. The ideal case would be for our grid (of squares now) to fill the rectangle completely, which would give us

a = c/r

where r and c are the numbers of rows and columns:

N = r*c

Multiplying/dividing 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 have to try the three options Frédéric mentioned and keep the one where r*c is smallest but still more than N:

  • floor(r), ceil(c)
  • ceil(r), floor(c)
  • ceil(r), ceil(c)