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)
您可以使用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()
方法的字符串中使用.使用此类生成的示例: