c – How to divide a canvas into my squares number


Basically what you are trying to achieve in other words is

  • You have given

    • dimensions (width * height)
    • amount of squares (squaresAmount)
    • squares are arranged in a grid (and without rotation)
  • You look for

  • So that

    • squareAmount squares of size squareSize are guaranteed to fit into width * height
    • squareSize is big as possible

So what you could do is something like e.g.

public float CalculateSquareSize(int width, int height, int squareAmount)
{
    var maxSquareSize = 0f;

    // Try to fit the squares by trying different numbers of columns and rows
    // we basically try every possible grid dimensions and fit them to the given width and height
    for (var columns = 1; columns <= squareAmount; columns++)
    {
        // Calculate the number of rows required to fit the squares
        // we use ceil here as one row might be incomplete 
        var rows = Mathf.CeilToInt((float)squareAmount / columns);

        // Ensure that the resulting grid still fits within the given dimensions
        if (columns <= width && rows <= height)
        {
            // Calculate the potential square size for this configuration
            var squareSizeForThisConfig = Mathf.Min(width / (float)columns, height / (float)rows);

            // Maximize the square size
            if (squareSizeForThisConfig > maxSquareSize)
            {
                maxSquareSize = squareSizeForThisConfig;
            }
        }
    }

    // Until here we only tried column wise layout with a potential incomplete row
    // but maybe a row wise layout with potentially incomplete column can fit bigger squareSize
    for (int rows = 1; rows <= squareAmount; rows++)
    {
        var columns = Mathf.CeilToInt((float)squareAmount / rows);

        if (columns <= width && rows <= height)
        {
            var squareSizeForThisConfig = Mathf.Min(width / (float)columns, height / (float)rows);

            if (squareSizeForThisConfig > maxSquareSize)
            {
                maxSquareSize = squareSizeForThisConfig;
            }
        }
    }

    return maxSquareSize;
}

If you want to additionally round this to a more “beautiful” square size you can of course still do so even though it would mean to give away a bit of the screen space

Leave a Reply

Your email address will not be published. Required fields are marked *