在imagettftext()中换行 [英] Wrap Text in imagettftext()
问题描述
我得到了这个脚本,可以根据目录中的随机jpg生成图像,并从数据库中添加随机标语:
i got this script to generate an image out of a random jpg in a directory, adding a random slogan from a database:
<?php
header('Content-type: text/html; charset=utf-8');
include '../connect.php';
require_once 'random.php';
$timestamp = time();
$date = date("d.m.Y_G", $timestamp);
$slogan = $mysqli->query("SELECT `text` FROM `slogans` ORDER BY RAND() LIMIT 1");
$slogan_txt = $slogan->fetch_assoc();
$bg = get_rand_img('../../images/');
$imgPath = '../../images/' .$bg;
$text = $slogan_txt[text];
$image = $imgPath;
$font = "font.TTF";
$font_size = "25";
$image_2 = imagecreatefromjpeg($image);
$black = imagecolorallocate($image_2,0,0,0);
$image_width = imagesx($image_2);
$image_height = imagesy($image_2);
$text_box = imagettfbbox($font_size,$angle,$font,$text);
$text_width = $text_box[2]-$text_box[0]; // lower right corner - lower left corner
$text_height = $text_box[3]-$text_box[1];
$x = ($image_width/2) - ($text_width/2);
$y = ($image_height/2) - ($text_height/2);
imagettftext($image_2,$font_size,0,$x,$y,$black,$font,$text );
header ("Content-type: image/png");
imagejpeg($image_2);
?>
到目前为止工作正常.
现在有一些口号在一行中用了很多字.我需要将它们包裹起来并且也要居中!
Now there are some slogans with to much words for one row. i need them to be wrapped and also be centered!
不能在imagettftext()中使用自动换行,所以我需要以某种方式使其爆炸.
can't use wordwrap in imagettftext(), so i need to explode it somehow.
我在网络上发现了一些功能,但是它们没有按预期工作.也许我只是不知道如何将它们与我现有的代码结合起来!
i found some functions on the web, but they dont work as expected. maybe i just dont know how to combine them with my existing code!
也许有人从自己的项目中得到了一个可行的例子?
maybe someone got a workign example from own projects?
到目前为止谢谢!
推荐答案
如果第一个字符串长于14,则它将爆炸一个字符串并将其放入第二个字符串中,我想您可以以此为基础.
This explodes a string and puts it text into a second string if the first is longer then 14, i guess you could build up on this.
$string = "";
$string2 = "";
$name = explode(" ", $name);
foreach ($name as $n) {
if (strlen($string) + strlen($n) > 14) {
$string2 .= $n . " ";
} else {
$string .= $n . " ";
}
}
要使文本居中,您需要执行以下操作: (imagesisex/2)-数字*像素大小
for centering the text you would need to do something like: (imagesisex/2) - digits * pixelsize
这篇关于在imagettftext()中换行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!