PHP文本到图像,文本对齐

时间:2015-05-07 11:08:09

标签: php alignment imagettftext

我在php中制作了一个小应用程序,它将文本放到图像中。我用imagettftext得到了它。我还能够使用此函数http://php.net/manual/en/function.imagettftext.php#89505将其放入具有特定宽度的imagettfbbox。我唯一的问题是我想要将文本对齐到框的右侧,如图像enter image description here

2 个答案:

答案 0 :(得分:0)

这是代码,但我不需要在X轴上将整个框对齐,而只需要将文本对齐。您可以将其映像为文本在html中

<p style="width:300px;text-align:right">This is the text to be wrapped and aligned to the right</p>
function wrap($fontSize, $angle, $fontFace, $string, $width){

    $ret = "";
    $arr = explode(' ', $string);
    foreach ( $arr as $word ){
        $teststring = $ret.' '.$word;
        $testbox = imagettfbbox($fontSize, $angle, $fontFace, $teststring);
        if ( $testbox[2] > $width ){
            $ret.=($ret==""?"":"\n").$word;
        } else {
            $ret.=($ret==""?"":' ').$word;
        }
    }
    return $ret;
}

function textToImage(){
    $pluginDir = plugin_dir_path( __FILE__ );
    $image = imagecreatefrompng($pluginDir . 'resources/img/image.png');
    $color = imagecolorallocate($image, 38, 64, 142);
    $font_path = $pluginDir . 'resources/font/DroidSans.ttf';
    $line = "This is the text to be wrapped and aligned to the right";

    imagettftext($image, 35, 0, 300, 600, $color, $font_path, wrap(18, 0, $font_path, $line, 300));

    imagepng($image, $pluginDir."resources/img/result.png");
    imagedestroy($image);
}

答案 1 :(得分:0)

您可以使用stil/gd-text课程。它为你做右对齐和文本包装。

<?php
use GDText\Box;
use GDText\Color;

$pluginDir = plugin_dir_path( __FILE__ );
$image = imagecreatefrompng($pluginDir . 'resources/img/image.png');

$textbox = new Box($image);
$textbox->setFontSize(35);
$textbox->setFontFace($pluginDir . 'resources/font/DroidSans.ttf');
$textbox->setFontColor(new Color(38, 64, 142));
$textbox->setBox(
    300, // distance from left edge
    600, // distance from top edge
    500, // textbox width
    500  // textbox height
);

// now we have to align the text horizontally and vertically inside the textbox
$textbox->setTextAlign('top', 'right');
// it can wrap multilined text
$textbox->draw("This is the text to be wrapped and aligned to the right");

imagepng($image, $pluginDir."resources/img/result.png");
imagedestroy($image);

演示:

demo