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 で、3 つのサムネイルがある場合、100 が返されるはずですが、代わりに 33 が返されます。