I want to center the text I add to my image using :
imagettftext($image, 85, 0, 250, 350, $color, $font, $txt );
I tried something like this :
$fontwidth1 = imagefontwidth($font);
$center1 = (imagesx($image)/2) - ($fontwidth1*(strlen($txt)/2));
However unfortunately it's not working. The imagefontwidth($font) part does not work :(
Anyone has faced this issue before and know an solution / alternative method ?
The function imagefontwidth
works best with fixed-width fonts. Like Austin Brunkhorst said, the most reliable way to get centered text uses imagettfbbox
, like so:
$bbox = imagettfbbox(85, 0, $font, $txt);
$center1 = (imagesx($image) / 2) - (($bbox[2] - $bbox[0]) / 2);