Created
March 11, 2022 22:04
-
-
Save andyg2/a907a263dafbd2565e9eb26e242de9df to your computer and use it in GitHub Desktop.
Grid to Coordinates / Coordinates to Grid
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// 10 pixel per grid | |
define('IMAGE_WH', 25); // Pixels | |
define('SQUARE_RC', 5); // Columns/Rows | |
define('IMAGE_SQ_RATIO', IMAGE_WH / SQUARE_RC); //10 | |
function cellToCoords($cell) { | |
$x = (($cell - 1) % SQUARE_RC) + 1; | |
$y = ceil($cell / SQUARE_RC); | |
$x *= IMAGE_SQ_RATIO; | |
$y *= IMAGE_SQ_RATIO; | |
// CENTER CELL: cell 1 = 5,5 | |
// $x -= IMAGE_SQ_RATIO / 2; | |
// $y -= IMAGE_SQ_RATIO / 2; | |
// $r = [$x, $y]; | |
// BOTTOM RIGHT: cell 1 = 10,10 | |
$r = [$x, $y]; | |
// TOP LEFT: cell 1 = 0,0 | |
// $x -= IMAGE_SQ_RATIO; | |
// $y -= IMAGE_SQ_RATIO; | |
// $r = [$x - 10, $y - 10]; | |
return ($r); | |
} | |
function coordsToGrid($x, $y) { | |
$calcX = $x / IMAGE_SQ_RATIO; | |
$calcY = (($y - IMAGE_SQ_RATIO) % SQUARE_RC) * SQUARE_RC; | |
return ($calcX + $calcY); | |
} | |
/// tests | |
$res = []; | |
$res['tests'] = range(1, SQUARE_RC); | |
foreach ($res['tests'] as $cell) { | |
$coords = cellToCoords($cell); | |
$res['image_coords'][$cell] = $coords; | |
$res['grid_numbers'][implode('-', $coords)] = coordsToGrid($coords[0], $coords[1]); | |
} | |
echo '<pre>'; | |
print_r($res); | |
echo '</pre>'; | |
?> | |
Array | |
( | |
[tests] => Array | |
( | |
[0] => 1 | |
[1] => 2 | |
[2] => 3 | |
[3] => 4 | |
[4] => 5 | |
) | |
[image_coords] => Array | |
( | |
[1] => Array | |
( | |
[0] => 5 | |
[1] => 5 | |
) | |
[2] => Array | |
( | |
[0] => 10 | |
[1] => 5 | |
) | |
[3] => Array | |
( | |
[0] => 15 | |
[1] => 5 | |
) | |
[4] => Array | |
( | |
[0] => 20 | |
[1] => 5 | |
) | |
[5] => Array | |
( | |
[0] => 25 | |
[1] => 5 | |
) | |
) | |
[grid_numbers] => Array | |
( | |
[5-5] => 1 | |
[10-5] => 2 | |
[15-5] => 3 | |
[20-5] => 4 | |
[25-5] => 5 | |
) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Regarding: Question 64401247
This is for a 10 pixel grid square, just divide coordinates by 10