ボタンの行が 1 つの場合は、ウィンドウの幅をボタンの数で割り、すべてのボタンの幅をその値に設定するだけです。
button.width = window.width / numberOfButtons;
button.height = window.height;
複数の行がある場合は、高さについても同じことをしてください。
button.width = window.width / numberOfButtonsH;
button.height = window.height / numberOfButtonsV;
ボタンをより適切なサイズにしたい場合は、希望するボタン数の平方根を 1 行のボタンの数として使用してみてください。必要なボタンの数が不均一な場合は、別の行を追加して、この行の最後のボタンを中央に配置します。
17 個のボタンの場合、5 行、最初の 4 行に 1 行あたり 4 つのボタン、最後の行に 1 つのボタンがあります。
次のように実行できます (一時的なデータ構造を使用するように編集されています)。
int width = 600;//replace those values with your own dimensions
int height = 600;
inline bool isUneven(const int i)
{
return (i%2);
}
struct tempButton
{
int x,y,w,h;
};
void populateWindow( const int requestedObjects = 18 )
{
int objectsPerRow = (int)floor(sqrt(requestedObjects));
int rows = objectsPerRow;
int diff = requestedObjects-rows*objectsPerRow;
tempButton tmp[requestedObjects];
if(diff>0)
{
++rows;// only needed for button dimension calculation, will be changed later
}
int buttonWidth = width / objectsPerRow;
int buttonHeight = height / rows;
int lastRowWidth = 0; width / diff;
for(int i=0; i<requestedObjects-diff; ++i)
{
tmp[i].h = buttonHeight;
tmp[i].w = buttonWidth;
}
if(diff>0)
{
lastRowWidth = width / diff;
for(int i=requestedObjects-diff; i<requestedObjects; ++i)
{
tmp[i].h = buttonHeight;
tmp[i].w = lastRowWidth;
}
--rows; // subtract one, because placing the last button on its own is easier
}
for(int i=0; i<rows; ++i)
{
for(int j=0; j<objectsPerRow; ++j)
{
tmp[j+i*objectsPerRow].x = j*buttonWidth; // set the positions
tmp[j+i*objectsPerRow].y = i*buttonHeight;
}
}
if(diff>0)
{
for(int i=requestedObjects-diff; i<requestedObjects; ++i)
{
tmp[i].x = (i-(requestedObjects-diff))*lastRowWidth;
tmp[i].y = rows*buttonHeight;
}
}
// now create the buttons using the temporary data
}