我有N个正方形。我有一个长方形盒子。我希望所有的方块都装在盒子里。我希望正方形尽可能大。
如何计算正方形的最大尺寸以使它们都适合盒子?
这适用于缩略图库中的缩略图。
int function thumbnailSize(
iItems, // The number of items to fit.
iWidth, // The width of the container.
iHeight, // The height of the container.
iMin // The smallest an item can be.
)
{
// if there are no items we don't care how big they are!
if (iItems = 0) return 0;
// Max size is whichever dimension is smaller, height or width.
iDimension = (iWidth min iHeight);
// Add .49 so that we always round up, even if the square root
// is something like 1.2. If the square root is whole (1, 4, etc..)
// then it won't round up.
iSquare = (round(sqrt(iItems) + 0.49));
// If we arrange our items in a square pattern we have the same
// number of rows and columns, so we can just divide by the number
// iSquare, because iSquare = iRows = iColumns.
iSize = (iDimension / iSquare);
// Don't use a size smaller than the minimum.
iSize = (iSize max iMin);
return iSize;
}
此代码当前工作正常。其背后的想法是取矩形容器的最小尺寸,假设容器是该尺寸的正方形,然后假设我们有相同数量的行和列,刚好足以容纳 iItems 正方形。
如果容器大多是方形的,这个函数就很好用。但是,如果您有一个长矩形,则缩略图会比实际显示的要小。例如,如果我的矩形是 100 x 300,并且我有三个缩略图,它应该返回 100,但返回 33。