假设所有矩形都具有相同的尺寸和方向,并且不应更改。
让我们玩!
// Proportion of the screen
// w,h width and height of your rectangles
// W,H width and height of the screen
// N number of your rectangles that you would like to fit in
// ratio
r = (w*H) / (h*W)
// This ratio is important since we can define the following relationship
// nbRows and nbColumns are what you are looking for
// nbColumns = nbRows * r (there will be problems of integers)
// we are looking for the minimum values of nbRows and nbColumns such that
// N <= nbRows * nbColumns = (nbRows ^ 2) * r
nbRows = ceil ( sqrt ( N / r ) ) // r is positive...
nbColumns = ceil ( N / nbRows )
Run Code Online (Sandbox Code Playgroud)
我希望我的数学是正确的,但这与您要寻找的相去甚远;)
编辑:比率与宽度和高度之间没有太大区别......
// If ratio = w/h
r = ratio * (H/W)
// If ratio = h/w
r = H / (W * ratio)
Run Code Online (Sandbox Code Playgroud)
然后你又回来使用 'r' 来找出使用了多少行和列。
您提到的行和列表明您设想将矩形排列在网格中,可能有一些空格(例如底行的一些)未填充。假设情况是这样:
假设您缩放对象,使它们(数量尚不清楚)n适合屏幕。然后
objectScale=screenWidth/(n*objectWidth)
Run Code Online (Sandbox Code Playgroud)
现在假设有N个对象,那么就会有
nRows = ceil(N/n)
Run Code Online (Sandbox Code Playgroud)
对象行(其中 ceil 是Ceiling 函数),这将占用
nRows*objectScale*objectHeight
Run Code Online (Sandbox Code Playgroud)
的垂直高度。我们需要找到n,并且想要选择最小的n使得这个距离小于screenHeight。
n由于上限函数的存在,简单的数学表达式变得更加棘手。如果列数相当小,最简单的查找方法可能n就是循环增加n,直到满足不等式为止。
编辑:我们可以用上限开始循环
floor(sqrt(N*objectHeight*screenWidth/(screenHeight*objectWidth)))
Run Code Online (Sandbox Code Playgroud)
对于 n,然后向下计算:然后在 O(sqrt(N)) 中找到解决方案。O(1) 解决方案是假设
nRows = N/n + 1
Run Code Online (Sandbox Code Playgroud)
或采取
n=ceil(sqrt(N*objectHeight*screenWidth/(screenHeight*objectWidth)))
Run Code Online (Sandbox Code Playgroud)
(Matthieu M. 的解决方案)但这些方法的缺点是 的值n可能不是最优的。
边界情况发生在N=0、 以及N=1和 对象的长宽比满足以下情况时objectHeight/objectWidth > screenHeight/screenWidth- 这两种情况都很容易处理。