Let's draw text on 400x300
image as example.
Horizontal center align
$im = imagecreatetruecolor(400, 300);
$c_black = imageColorAllocate($im, 0,0,0);
$c_green = imageColorAllocate($im, 46,204,64);
$text = 'Hi';
$font = '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf';
$p = imagettfbbox(40, 0, $font, $text);
imagettftext($im, 40, 0, (400 - $p[2])/2, 100, $c_green, $font, $text);
imagePng($im, '/tmp/image.png');
We use (400 - $p[2])/2
to calculate x
coordinate so our text is centered horizontally. Open original or edit on Github.
Vertical and horizontal center align
$im = imagecreatetruecolor(400, 300);
$c_black = imageColorAllocate($im, 0,0,0);
$c_green = imageColorAllocate($im, 46,204,64);
$text = 'Hi';
$font = '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf';
$p = imagettfbbox(40, 0, $font, $text);
imagettftext($im, 40, 0, (400 - $p[2])/2, (300 - $p[5])/2, $c_green, $font, $text);
imagePng($im, '/tmp/image.png');
We've used (400
- $p[2])/2to center align text horizontally and
(300- $p[5])/2
to get y
coordinate so our text is also centered vertically.
Top comments (0)