3
\$\begingroup\$

Just made it with some more investigation thanks to this site: Hexagonal grid math, but the hexagons have a little bit spacing horizontally.

Here is the code:

include('class/hexagon.php');

$hexagon = new hexagon(16);

$png_image = imagecreate(500, 500);
imagecolorallocate($png_image, 255, 255, 255);
$black = imagecolorallocate($png_image, 0, 0, 0);

for($i=1;$i<12;$i++) {
    for($j=1;$j<10;$j++) {
        $x = $i * $hexagon->ver;
        $y = $j * $hexagon->height + ( ($i%2) * ( $hexagon->height / 2 ) ); 
        $points = $hexagon->drawHex($x,$y);
        $last_line = array($points[0][0],$points[0][1]);
        imagettftext ($png_image , 5 , 0 , $x , $y , $black , "C:/Windows/Fonts/Arial.ttf" , "{$i},{$j}" );
        foreach($points as $c):
            imageline($png_image, $last_line[0], $last_line[1], $c[0], $c[1], $black);
            $last_line = $c;
        endforeach;                 
    }
}
header('Content-type: image/png');
imagepng($png_image);
imagedestroy($png_image);

class hexagon {
    public $size;
    public $width;
    public $height;
    public $hor;
    public $ver;
    public $angle;
    public $rad_angle;
    public $side;
    public function __construct($xsize = 32) {
        $this->angle = 60;
        $this->rad_angle = $this->angle * (pi() / 180);
        $this->side = $this->size * cos($this->rad_angle);
        $this->size = $xsize;
        $this->width = $this->size * 2;
        $this->height = $this->width * sin($this->angle * (pi()/180));
        $this->hor = $this->width * ( 3/4 );
        $this->ver = $this->height;
    }

    public function drawHex($x, $y) {
        $points = array();
        for($i=0;$i<7;$i++) {
            $angle_deg = $this->angle * $i;
            $angle_rad = pi() / 180 * $angle_deg;
            $points[$i] = array($x + $this->size * cos($angle_rad),$y + $this->size * sin($angle_rad));
        }
        return $points;
    }
}

Result:

enter image description here

Any advice?

\$\endgroup\$
2
\$\begingroup\$

Just fixed by doing the X coordinate with

$x = $hexagon->ver + $i * $hexagon->size * 1.5;

Looks beautiful now. enter image description here

\$\endgroup\$
1
  • \$\begingroup\$ Glad to hear you solved your problem! Please mark this as the accepted answer - helps others with similar problems find solutions. \$\endgroup\$
    – Pikalek
    May 12 '18 at 15:08

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .