开发者

Get width of a single character from ttf-font in php?

开发者 https://www.devze.com 2022-12-23 06:36 出处:网络
I\'m creating an dynam开发者_高级运维ic image, which creates headers on my page using PHPs GD-library. The problem is, that I need a line-wrapping system. It\'s not a problem itself, but first I need

I'm creating an dynam开发者_高级运维ic image, which creates headers on my page using PHPs GD-library. The problem is, that I need a line-wrapping system. It's not a problem itself, but first I need to get the width (in pixels) of current character.

I'm pretty curious about this, is there any way? Or do I need to manually specify width of every abc?

Martti Laine


You would have to do a imagettfbbox() on each single character.

Untested but should work:

$string = "Lorem Ipsum";
$size = 20;
$angle = 0;
$fontfile = "ARIAL.TTF";

$strlen = strlen($string);
for ($i = 0; $i < $strlen; $i++)
 {
    $dimensions = imagettfbbox($size, $angle, $fontfile, $string[$i]);
    echo "Width of ".$string[$i]." is ".$dimensions[2]."<br>";

 }


If you print the results of

$string = "Lorem Ipsum";
$size = 20;
$angle = 0;
$fontfile = "./fonts/arial.ttf";

$dimensions = imagettfbbox($size, $angle, $fontfile, $string); 
print_r($dimensions);

you might get something` like:

Array
(
    [0] => -1
    [1] => 5
    [2] => 152
    [3] => 5
    [4] => 152
    [5] => -20
    [6] => -1
    [7] => -20
)

where each index is:

0   lower left corner, X position
1   lower left corner, Y position
2   lower right corner, X position
3   lower right corner, Y position
4   upper right corner, X position
5   upper right corner, Y position
6   upper left corner, X position
7   upper left corner, Y position

So the width should be index 2 - index 0. I dont quite get the minus 1 for index 0.

It is a bit odd that if you sum the total of each char in the string the results is 130 not 153.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号