I have a # of images that I\'m stitching together into a sprite sheet, how can I calculate the number of rows and columns to fit equally in an even rectangle (no blank space
Since it's unlikely you'll have a large number to begin with there are a lot of ways you can proceed in factoring it.
See Best way to find all factors of a given number in C# for some of them.
The simplest is: - Loop from 1 to the square root of the number, call the index "i".
This will give you all the integers that divide your number N. The "other" number is, of course, obtained by dividing N by that integer.
Then, you need to pick the best pair according to some rule. You can chose the ones with the smallest difference: if a * b = N
, choose the ones with the smallest absolute value of (a-b)
Here's a very fast and easy algorithm (where N is the number of images)
rows = floor(sqrt(N))
while(N % rows != 0)
rows = rows - 1
And rows
will be the number of rows needed. Columns can obviously be found with N / rows
.
I hope this helps!
Well looking at it if the number is prime you want to have 1 row with x columns where x is the prime number. Else if the number is a perfect square the rows would be the square root of the number by the square root of the number (9 == 3x3) . Else factor the remainder.
What's your priority? Do you want it to have the difference between height, width to be minimum, or anything like that?
Given the number n of images. You should take every number i from 1 to sqrt(n). If n can be divided by i (n%i ==0), divide and increment an array power[i] each time it divides. If n cannot be divided any more by i (aka n%i != 0) increment i else divide again.
You should get all the divisors and their biggest power in a given number n.
Make combinations of these and you will get the dimensions of your square.
Take a look into Integer Factorization
Maybe that is what you need.
Seems like you have to find all factor pairs of the number, then pick the pair the gives you the most 'desirable' row:column ratio.
So for example:
bestRows = 1
bestRatio = ((double) 1) / N;
for (int i : 1 to N) {
if ((N % i) == 0) {
r = N % i
c = N / i
ratio = ((double) r) / N;
if (firstIsBetter(ratio, bestRatio)) {
bestRows = r;
bestRatio = ratio;
}
}
}