imagestring-获取以像素为单位的字符串长度的大小

ipr*_*esy -1 php png canvas image pixels

您好,只想提前提到,这不是重复的。我已经看过类似的文章,但是所有这些文章都使用了特定的字体,但事实并非如此。我使用的是默认字体编号3(对于此示例),我希望能够计算输出大小并将其放在$ canvas的确切中心

imagestring($canvas,3,imagesx($canvas),imagesy($canvas),$myString,imagecolorallocate($canvas,239,13,177));
Run Code Online (Sandbox Code Playgroud)

我知道如何进行计算以使其居中,这很容易,唯一遗漏的参数是考虑字体号3的字符串的精确像素大小(x / y)。考虑字体号3的字符串的像素(x / y) 3。

小智 5

更新了答案而不使用特定字体。PHP嵌入式字体确实是等宽的(经过测试并可以正常工作):

$font           = 3;
$img            = imagecreatetruecolor(500, 500);
$text           = "Waldson Patricio";
$color          = imagecolorallocate($img, 255, 255, 255);
$size           = strlen($text);

$tw             = $size * imagefontwidth($font);
$th             = imagefontheight($font);



imagestring($img, $font, (imagesx($img) - $tw) / 2 , (imagesy($img) - $th) / 2, $text, $color);
header('Content-type:image/jpeg');
imagejpeg($img);
Run Code Online (Sandbox Code Playgroud)