I'm looking for a maths equation to find out what size tiles are needed to fit into a rectangle.
This is for a community banner of members' profile pictures.
the size of the rectangle will change. and the images are always square.
For the example lets do 100px X 10px (this will change on request of banner size)
The total number of images is 1000 (this will change as new members join)
this is what I have so far.
$xsize = 100;
$ysize = 10;
$images = 1000;
$totalarea = $xsize * $ysize;
$imagesize = $totalarea / $images;
echo $imagesize;
This will echo 1 which is correct, but if we apply this to
$xsize = 1920;
$ysize = 500;
$images = 50;
$totalarea = $xsize * $ysize;
$imagesize = $totalarea / $images;
echo $imagesize;
this echoes 19200 which is wrong.
Any help with this is much-appreciated maths was not my strongest point and I feel I have fried my brain trying to understand this.
There are many questions based on what I'm asking here but none in PHP
CodePudding user response:
You're distributing a total area X between Y Images
$imagesize = $totalarea / $images;
this gives you the average area of each images. (px²)
If you need to know its size and since the images are squared, you need to convert their area to the length of a side (the square root of a square gives its side) :
$xsize = 1920;
$ysize = 500;
$images = 50;
$totalarea = $xsize * $ysize;
$imageArea = $totalarea / $images;
$imageSideSize = sqrt($imageArea);
echo $imageSideSize; // 138.56406460551
In the first example, you get the correct result because sqrt(1) == 1
, side length is the same than area
CodePudding user response:
Credit for the algorithm is entirely from chubakueno's answer. For more algo details please click here.
I am writing php version of it here.
$x = 1920; // x size
$y = 500; // y size
$n = 50; // Images
$px = ceil(sqrt($n*$x/$y));
if (floor($px*$y/$x) * $px<$n) {
$sx = $y/ceil($px*$y/$x);
} else {
$sx = $x/$px;
}
$py = ceil(sqrt($n*$y/$x));
if (floor($py*$x/$y) * $py<$n) {
$sy = $x/ceil($x*$py/$y);
} else {
$sy = $y/$py;
}
echo max($sx,$sy);
// Output
// x=100, y=10, $images=1000 -> 1
// x=1920, y=500, $images=50 -> 125