我无法得到对我有用的这个问题的答案,但我从Neptilo 找到了一个类似问题的简洁实现。但它不适用于矩形,仅适用于正方形。所以我应用mckeed 的想法来规范化矩形,然后按照正方形的算法。
结果是fitToContainer() 函数。给它适合n、containerWidth 和containerHeight 以及原始itemWidth 和itemHeight 的矩形数量。如果项目没有原始宽度和高度,请使用itemWidth 和itemHeight 指定所需的项目比例。
例如,fitToContainer(10, 1920, 1080, 16, 9) 的结果是 {nrows: 4, ncols: 3, itemWidth: 480, itemHeight: 270},因此 480 x 270(像素或任何单位)的四列和 3 行。
要在 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 }
}