Algorithm 布局算法
我有一个由N张图片组成的数组,每张图片的尺寸都是WxH。我想把它们显示在一个尽可能接近正方形的矩形矩阵中。最后一行可能不完整。如何计算行数和列数?(第一次尝试完全错误.) (第二次尝试也是如此) 第三次尝试:Algorithm 布局算法,algorithm,Algorithm,我有一个由N张图片组成的数组,每张图片的尺寸都是WxH。我想把它们显示在一个尽可能接近正方形的矩形矩阵中。最后一行可能不完整。如何计算行数和列数?(第一次尝试完全错误.) (第二次尝试也是如此) 第三次尝试: columns = floor( sqroot( N * H / W ) + 0.5 ) rows = ceiling( N / columns ) 如果N足够小,您可以尝试所有可能的布局 Score(N, W, H, columnCount): rowCount = ceili
columns = floor( sqroot( N * H / W ) + 0.5 )
rows = ceiling( N / columns )
如果N足够小,您可以尝试所有可能的布局
Score(N, W, H, columnCount):
rowCount = ceiling(N / columnCount)
xPixels = W * columnCount
yPixels = H * rowCount
return min(xPixels, yPixels) / max(xPixels, yPixels)
bestColumnCount = columnCount with max Score(N, W, H, columnCount) in [1,N]
bestRowCount = ceiling(N / bestColumnCount)
因此,假设你有p横穿,q向下;那么你的整个图像是pW乘以qH。你想包括所有图像,所以pq>=N;只有最后一行是不完整的,所以p(q-1)
条件N
target_ratio = H/W;
p = round(sqrt(N*H/W)); // initial guess
current_ratio = p / ceiling(N/p);
merit = merit_function(current_ratio, target_ratio);
best_p = p; best_merit = merit; prev_merit = merit;
// [define merit_function however you like; e.g., -abs(log(x/y)-1)
// or -max(x/y-1,y/x-1) or whatever.]
if (current_ratio > target_ratio) {
// p might be too big
while (true) {
--p; if (p<=0) break;
current_ratio = p / ceiling(N/p);
merit = merit_function(current_ratio, target_ratio);
if (merit > best_merit) { best_p=p; best_merit=merit; }
else if (merit < prev_merit) break;
prev_merit = merit;
}
}
else if (current_ratio < target_ratio) {
// p might be too small
// similar loop, but in the other direction
}