Skip to content

Instantly share code, notes, and snippets.

@andyg2
Created March 11, 2022 22:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andyg2/a907a263dafbd2565e9eb26e242de9df to your computer and use it in GitHub Desktop.
Save andyg2/a907a263dafbd2565e9eb26e242de9df to your computer and use it in GitHub Desktop.
Grid to Coordinates / Coordinates to Grid
<?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
)
)
@andyg2
Copy link
Author

andyg2 commented Mar 11, 2022

Regarding: Question 64401247
This is for a 10 pixel grid square, just divide coordinates by 10

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment