php imagettftext字母间距

rad*_*0_0 6 php gd imagettftext

有没有人有一个绘制带有指定字母间距的ttf字符串(imagettftext)的函数?

我找不到任何内置GD功能,所以我认为应该逐字逐句地添加一些恒定的宽度.

也许有人已经有这样的功能:)

PS.最好的字体是arial.ttf

rad*_*0_0 23

function imagettftextSp($image, $size, $angle, $x, $y, $color, $font, $text, $spacing = 0)
{        
    if ($spacing == 0)
    {
        imagettftext($image, $size, $angle, $x, $y, $color, $font, $text);
    }
    else
    {
        $temp_x = $x;
        for ($i = 0; $i < strlen($text); $i++)
        {
            $bbox = imagettftext($image, $size, $angle, $temp_x, $y, $color, $font, $text[$i]);
            $temp_x += $spacing + ($bbox[2] - $bbox[0]);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

和电话:

imagettftextSp($image, 30, 0, 30, 30, $black, 'arial.ttf', $text, 23);
Run Code Online (Sandbox Code Playgroud)

函数参数顺序符合标准的imagettftext参数顺序,最后一个参数是可选的$ spacing参数.如果未设置或传递的值为0,则不设置字距调整/字母间距.


小智 10

我知道这回答了一段时间,但我需要一个具有字母间距并保持角度偏移的解决方案.

我修改了radzi的代码来完成这个:

function imagettftextSp($image, $size, $angle, $x, $y, $color, $font, $text, $spacing = 0)
{        
    if ($spacing == 0)
    {
        imagettftext($image, $size, $angle, $x, $y, $color, $font, $text);
    }
    else
    {
        $temp_x = $x;
        $temp_y = $y;
        for ($i = 0; $i < strlen($text); $i++)
        {
            imagettftext($image, $size, $angle, $temp_x, $temp_y, $color, $font, $text[$i]);
            $bbox = imagettfbbox($size, 0, $font, $text[$i]);
            $temp_x += cos(deg2rad($angle)) * ($spacing + ($bbox[2] - $bbox[0]));
            $temp_y -= sin(deg2rad($angle)) * ($spacing + ($bbox[2] - $bbox[0]));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 很高兴看到您将这个答案反馈给了Stack Overflow社区。好秀+1 (2认同)

小智 6

只是为了完成pidalia的答案(这是最好的),以避免使用特殊字符(如"é"或"à")的一些麻烦

static function imagettftextSp($image, $size, $angle, $x, $y, $color, $font, $text, $spacing = 0) {
    if ($spacing == 0) {
        imagettftext($image, $size, $angle, $x, $y, $color, $font, $text);
    } else {
        $temp_x = $x;
        $temp_y = $y;
        //to avoid special char problems
        $char_array = preg_split('//u',$text, -1, PREG_SPLIT_NO_EMPTY);
        foreach($char_array as $char) {
            imagettftext($image, $size, $angle, $temp_x, $temp_y, $color, $font, $char);
            $bbox = imagettfbbox($size, 0, $font, $char);
            $temp_x += cos(deg2rad($angle)) * ($spacing + ($bbox[2] - $bbox[0]));
            $temp_y -= sin(deg2rad($angle)) * ($spacing + ($bbox[2] - $bbox[0]));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)