Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center text between 2 points php?

Tags:

php

image

I am trying to center some text between to points. The text is dynamic and should be centered no matter what it contains.

I am trying the following:

    $dims = imagettfbbox(130, 0, './Calibri.ttf', "JULY");

$width = ($dims[2])-($dims[0]);

imagettftext($my_img , 130, 0, 1196-($width/2) , 700, $text_colour, './Calibri.ttf', "JULY");

I have a point at x = 711 and a point at x = 1907 and this is where I get the 1196 from because 1907-711 = 1196.

In my logic the 1196-($width/2) should work as the parameter is the first pixel of the text.

But as it can be seen on the image, it is not centered. My test

like image 335
RamHS Avatar asked Feb 23 '26 12:02

RamHS


1 Answers

From your explanation I understood that 1196-($width/2) is wrong.

You should find the middle of the box, laying between x = 711 and x = 1907:

$x_center = 711 + (1907 - 711) / 2 
$x_start = $x_center - ($width / 2)

Hope it helps.

like image 184
Aleksei Matiushkin Avatar answered Feb 26 '26 00:02

Aleksei Matiushkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!