我在用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”就可以了,但文字是动态的。
有什么建议吗?
最好的问候
答案 0 :(得分:0)
我会在一行上创建一个临时图像,将累积的长度存储在一个数组中。然后准确确定哪一个单词适合一行,并确定每行中心的偏移量。然后创建图像。
或者,您可以为每一行创建单独的图像,然后将它们与正确的偏移相结合。