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.
精彩评论