【发布时间】:2012-03-15 21:35:33
【问题描述】:
我正在尝试在图像上打印多行文本并将它们居中对齐。
即
这是
一串文本
现在,我只有整个字符串的左侧位置。让它工作的任何捷径?我认为它可能必须是整个字符串上的 getttfbox,然后在换行符上爆炸,然后将新文本居中在那个更大的 ttfbox 内。真是头疼啊……
编辑:想出了一个解决方案:
foreach ( $strings as $index => $string ) {
$parts = explode ( "\n", $string['string'] );
if ( count ( $parts ) > 1 ) {
$bounds = imagettfbbox ( intval($string['fontsize']), 0, $font, $string['string'] );
$width = $bounds[2] - $bounds[0];
$height = $bounds[3] - $bounds[5];
$line_height = $height / count ( $parts );
foreach ( $parts as $index => $part ) {
$bounds = imagettfbbox ( intval($string['fontsize']), 0, $font, $part );
$new_width = $bounds[2] - $bounds[0];
$diff = ( $width - $new_width ) / 2;
$new_left = $string['left'] + $diff;
$new_string = $string;
$new_string['left'] = $new_left;
$new_string['top'] = $string['top'] + ($index * $line_height);
$new_string['string'] = $part;
$new_strings[] = $new_string;
}
}
}
if ( $new_strings )
$strings = $new_strings;
在这种情况下,每个 $string 都是一个数组,其中包含一些关于如何打印以及打印什么的信息。 希望对某人有所帮助。
【问题讨论】:
-
请不要将您的答案编辑到您的问题中,而是写一个新答案(并接受它,如果那是对您有用的解决方案)。