将N#个正方形调整为尽可能大,同时仍然适合X个Y维的方框.(缩略图!)

Jak*_*ake 5 resize thumbnails aspect-ratio

我有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;
 }
Run Code Online (Sandbox Code Playgroud)

此代码目前正常.它背后的想法是采取矩形容器的最小尺寸,假装容器是该维度的正方形,然后假设我们有相同数量的行和列,刚好足以适合内部的iItems方块.

如果容器大部分为方形,则此功能很有效.但是,如果你有一个长矩形,那么缩略图会比它们更小.例如,如果我的矩形是100 x 300,并且我有三个缩略图,它应该返回100,而是返回33.

Car*_*ten 6

可能不是最优的(如果它没有尝试我的工作),但我认为比你当前的方法更好:

w:矩形的宽度

h:矩形的高度

n:图像数量

a = w*h:矩形的面积.

ia =理想情况下图像的最大面积.

il = sqrt(ia)理想情况下图像的最大长度.

nw = round_up(w/il):您需要堆叠在一起的图像数量.

nh = round_up(h/il):您需要彼此堆叠的图像数量.

l = min(w/nw,w/nh):要使用的图像的长度.