使用imagettftext(),PHP右对齐图像中的文本

Jam*_*son 24 php gd image imagettftext

我正在为我的用户设置动态论坛签名图像,我希望能够将他们的用户名放在图像上.我能够做到这一点很好,但由于用户名是不同的长度,我想对齐用户名,当我必须设置x和y坐标时,我怎么能这样做.

$im = imagecreatefromjpeg("/path/to/base/image.jpg");
$text = "Username";
$font = "Font.ttf";
$black = imagecolorallocate($im, 0, 0, 0);

imagettftext($im, 10, 0, 217, 15, $black, $font, $text);
imagejpeg($im, null, 90);
Run Code Online (Sandbox Code Playgroud)

And*_*hea 61

使用imagettfbbox函数获取字符串的宽度,然后从图像的宽度中减去该字符串以获得起始x坐标.

$dimensions = imagettfbbox($fontSize, $angle, $font, $text);
$textWidth = abs($dimensions[4] - $dimensions[0]);
$x = imagesx($im) - $textWidth;
Run Code Online (Sandbox Code Playgroud)


sti*_*til 6

您可以使用stil/gd-text类.免责声明:我是作者.

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

$im = imagecreatefromjpeg("/path/to/base/image.jpg");

$textbox = new Box($im);
$textbox->setFontSize(12);
$textbox->setFontFace("Font.ttf");
$textbox->setFontColor(new Color(0, 0, 0)); // black
$textbox->setBox(
    50,  // distance from left edge
    50,  // distance from top edge
    200, // textbox width
    100  // textbox height
);

// text will be aligned inside textbox to right horizontally and to top vertically
$textbox->setTextAlign('right', 'top');

$textbox->draw("Username");
Run Code Online (Sandbox Code Playgroud)

您还可以绘制多行文字.只需\n在传递给draw()方法的字符串中使用.使用此类生成的示例:

右对齐文本演示


Pek*_*ica 5

使用imagettfbbox()预先计算用户名的大小。

从那里获得的宽度,您可以扣除文本需要开始的 x 位置。