Knowing width and height of grid where the amount of elements are known?
I've stumpled upon a problem that I can't solve. I am given the amount of elements to populate a grid with, but through this, I need to know (beforehand) what the width and height (in amount of elements) the grid should be.
I would like the aspect ratio between width and height of the grid to be 1:1. Even with this simple aspect ratio, I fail at doing the c开发者_C百科alculations.
Could someone help me?
Example provided below
Let's say I have 9 elements in total. The width and height of the grid would then be 3. This is easy (by using the square root of the amount of elements).
But what about (for instance) 10 elements, or 11? With 10 elements, I would like either the width or height of the grid to be 4. Same with 11.
How do I perform these calculations?
It all depends on how you want to handle non-square layouts. Either way, though, you can take the square root of the number of items, and then take either the floor or ceiling to get the desired width/height.
For example, Math.Sqrt(11)
is ~3.3166, so Math.Ceiling(Math.Sqrt(11)) == 4
, which is your desired height/width.
精彩评论