我无法得到这个问题的答案来为我工作,但我找到了一个针对Neptilo的类似问题的简洁实现。但它不适用于矩形,仅适用于正方形。所以我应用mckeed的想法来规范化矩形,然后按照正方形的算法。
结果就是fitToContainer()
函数。给它适合的矩形数量n
,containerWidth
andcontainerHeight
和原始的itemWidth
and itemHeight
。如果项目没有原始宽度和高度,请使用itemWidth
和itemHeight
指定项目的所需比例。
例如,fitToContainer(10, 1920, 1080, 16, 9)
结果为{nrows: 4, ncols: 3, itemWidth: 480, itemHeight: 270}
4 列和 3 行,大小为 480 x 270(像素,或任何单位)。
为了在 1920x1080 的相同示例区域中放置 10 个正方形,您可以调用fitToContainer(10, 1920, 1080, 1, 1)
导致{nrows: 2, ncols: 5, itemWidth: 384, itemHeight: 384}
.
function fitToContainer(n, containerWidth, containerHeight, itemWidth, itemHeight) {
// We're not necessarily dealing with squares but rectangles (itemWidth x itemHeight),
// temporarily compensate the containerWidth to handle as rectangles
containerWidth = containerWidth * itemHeight / itemWidth;
// Compute number of rows and columns, and cell size
var ratio = containerWidth / containerHeight;
var ncols_float = Math.sqrt(n * ratio);
var nrows_float = n / ncols_float;
// Find best option filling the whole height
var nrows1 = Math.ceil(nrows_float);
var ncols1 = Math.ceil(n / nrows1);
while (nrows1 * ratio < ncols1) {
nrows1++;
ncols1 = Math.ceil(n / nrows1);
}
var cell_size1 = containerHeight / nrows1;
// Find best option filling the whole width
var ncols2 = Math.ceil(ncols_float);
var nrows2 = Math.ceil(n / ncols2);
while (ncols2 < nrows2 * ratio) {
ncols2++;
nrows2 = Math.ceil(n / ncols2);
}
var cell_size2 = containerWidth / ncols2;
// Find the best values
var nrows, ncols, cell_size;
if (cell_size1 < cell_size2) {
nrows = nrows2;
ncols = ncols2;
cell_size = cell_size2;
} else {
nrows = nrows1;
ncols = ncols1;
cell_size = cell_size1;
}
// Undo compensation on width, to make squares into desired ratio
itemWidth = cell_size * itemWidth / itemHeight;
itemHeight = cell_size;
return { nrows: nrows, ncols: ncols, itemWidth: itemWidth, itemHeight: itemHeight }
}