PHP GD居中多行(动态文本)

PHP GD居中多行(动态文本),php,gd,Php,Gd,Im在以GD库为中心的图像上动态绘制文本 对齐所有直线中心的最佳方法是什么 <?php function imagettfstroketext(&$image, $size, $angle, $x, $y, &$textcolor, &$strokecolor, $fontfile, $text, $px) { for($c1 = ($x-abs($px)); $c1 <= ($x+abs($px)); $c1++) for($c2

Im在以GD库为中心的图像上动态绘制文本

对齐所有直线中心的最佳方法是什么

<?php


function imagettfstroketext(&$image, $size, $angle, $x, $y, &$textcolor, &$strokecolor, $fontfile, $text, $px) {
    for($c1 = ($x-abs($px)); $c1 <= ($x+abs($px)); $c1++)
        for($c2 = ($y-abs($px)); $c2 <= ($y+abs($px)); $c2++)
            $bg = imagettftext($image, $size, $angle, $c1, $c2, $strokecolor, $fontfile, $text);
   return imagettftext($image, $size, $angle, $x, $y, $textcolor, $fontfile, $text);
}



$image = "12.png"; 
$font = "./impact.ttf";
$font_size = "50";

$image_2 = imagecreatefrompng($image);
$black = imagecolorallocate($image_2, 255,255,255);
$black2 = imagecolorallocate($image_2, 0,0,0);

$image_width = imagesx($image_2);  
$image_height = imagesy($image_2);
$margin = 35;


$text = "This is the Text. It is dynamically long. This text will be split using the function under this text.";

//explode text by words
$text_a = explode(' ', $text);
$text_new = '';
foreach($text_a as $word){
    //Create a new text, add the word, and calculate the parameters of the text
    $box = imagettfbbox($font_size, 0, $font, $text_new.' '.$word);
    //if the line fits to the specified width, then add the word with a space, if not then add word with new line
    if($box[2] > $image_width - $margin*2){
        $text_new .= "\n".$word;
    } else {
        $text_new .= " ".$word;
    }
}

$text_box = imagettfbbox($font_size,0,$font,$text_new);
$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);


$font_color = imagecolorallocate($image_2, 255, 255, 255);
$font_color2 = imagecolorallocate($image_2, 0, 0, 0);
$stroke_color = imagecolorallocate($image_2, 0, 0, 0);

$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);
$grey = imagecolorallocate($im, 175, 175, 175);


imagettfstroketext($image_2, $font_size ,0,$x,$y,$font_color, $stroke_color, $font, $text_new, 0);

header ("Content-type: image/png");
imagejpeg($image_2, "../img/output.png");
   imagedestroy($image_2);

?>

这就是它现在的样子:

它应该是这样的:

使用三次“imagettfstroketext”并添加“$y+50”就可以了,但文本是动态的

有什么建议吗


致以最诚挚的问候

我会在一行上创建一个临时图像,将累积长度存储在一个数组中。然后准确地确定哪一个单词适合一行,以及每一行的中心偏移量。然后创建图像

或者,您可以为每一行创建单独的图像,然后将它们与右偏移组合。

可能的重复