PHP拱形文本图像

时间:2016-10-04 13:41:22

标签: php image

我尝试生成拱形文本并将其合并到图像功能区中,如下所示:

enter image description here

但是我一直在使用以下脚本,这导致文本围绕圆圈产生电弧。问题是我需要将文本完全放在功能区内,如拱形而不是弧形。

以下代码:

    <?php

    $im = imagecreate(400,400);

    $white = imagecolorallocate($im, 0xFF, 0xFF, 0xFF);
    $grey  = imagecolorallocate($im, 0xCC, 0xCC, 0xCC);
    $txtcol = imagecolorallocate($im, 0xFF, 0x00, 0x00);

    $r = 150;
    $cx = 200;
    $cy = 200;
    $txt1 = 'Text on an Arc';
    $txt2 = 'by Barand';
    $font = 'arial.ttf';
    #$font = 'bauhausm.ttf';
    $size = 48;



    imagearc($im,$cx,$cy,$r*2,$r*2,$s,$e,$grey);
    $pad = 2;                      // extra char spacing for text
    $s = 180;
    $e = 360;
    textOnArc($im,$cx,$cy,$r,$s,$e,$txtcol,$txt1,$font,$size,$pad);
    $pad = 6;                      // extra char spacing for text
    $s = 0;
    $e = 180;
    textInsideArc($im,$cx,$cy,$r,$s,$e,$txtcol,$txt2,$font,$size,$pad);

    header("content-type: image/png");
    imagepng($im);
    imagedestroy($im);

    function textWidth($txt, $font, $size)
    {
        $bbox = imagettfbbox($size,0,$font,$txt);
        $w = abs($bbox[4]-$bbox[0]);
        return $w;
    }

    function textOnArc($im,$cx,$cy,$r,$s,$e,$txtcol,$txt,$font,$size, $pad=0)
    {
        $tlen = strlen($txt);
        $arccentre = ($e + $s)/2;
        $total_width = textWidth($txt, $font, $size) - ($tlen-1)*$pad;
        $textangle = rad2deg($total_width / $r);
        $s = $arccentre - $textangle/2;
        $e = $arccentre + $textangle/2;
        for ($i=0, $theta = deg2rad($s); $i < $tlen; $i++)
        {
            $ch = $txt{$i};
            $tx = $cx + $r*cos($theta);
            $ty = $cy + $r*sin($theta);
            $dtheta = (textWidth($ch,$font,$size))/$r;
            $angle = rad2deg(M_PI*3/2 - ($dtheta/2 + $theta) );
            imagettftext($im, $size, $angle, $tx, $ty, $txtcol, $font, $ch);
            $theta += $dtheta;
        }
    }

    function textInsideArc($im,$cx,$cy,$r,$s,$e,$txtcol,$txt,$font,$size, $pad=0)
    {
        $tlen = strlen($txt);
        $arccentre = ($e + $s)/2;
        $total_width = textWidth($txt, $font, $size) + ($tlen-1)*$pad;
        $textangle = rad2deg($total_width / $r);
        $s = $arccentre - $textangle/2;
        $e = $arccentre + $textangle/2;
        for ($i=0, $theta = deg2rad($e); $i < $tlen; $i++)
        {
            $ch = $txt{$i};
            $tx = $cx + $r*cos($theta);
            $ty = $cy + $r*sin($theta);
            $dtheta = (textWidth($ch,$font,$size)+$pad)/$r;
            $angle = rad2deg(M_PI/2 - ($theta - $dtheta/2));
            imagettftext($im, $size, $angle, $tx, $ty, $txtcol, $font, $ch);
            $theta -= $dtheta;
        }
    }

    ?>

我认为这会最好地说明问题:

enter image description here

0 个答案:

没有答案