简体   繁体   English

从php中的ttf-font获取单个字符的宽度?

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

I'm creating an dynamic image, which creates headers on my page using PHPs GD-library. 我正在创建一个动态图像,它使用PHP 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? 或者我是否需要手动指定每个abc的宽度?

Martti Laine Martti Laine

You would have to do a imagettfbbox() on each single character. 你必须在每个单个字符上做一个imagettfbbox()

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. 所以宽度应该是索引2 - 索引0.我没有得到索引0的减1。

It is a bit odd that if you sum the total of each char in the string the results is 130 not 153. 如果你对字符串中每个字符的总和求和,结果是130而不是153,这有点奇怪。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM