PHP-GD:试图将文本居中,但它在水平方向偏离中心显示

问题描述

下面的 PHP 代码应该将字母“M”垂直和水平居中。垂直方向完全居中,但水平方向关闭

真正奇怪的是偏移量看起来是正确的,但它似乎放置在与我所说的不同的坐标处。 (正确的起始 X 偏移量应该是 10,但它似乎位于 16 像素之后)。

M text off-center

<?PHP

header('Content-Type: image/png');

$image = imagecreatetruecolor(100,400);

$font_size = 92;
$font = "RobotoCondensed-Bold.ttf"; // FILE PATH TO FONT
$angle = 0;
$text = "M";
$red = imagecolorallocate($image,255,0);
$white = imagecolorallocate($image,255);

// Get image dimensions
$image_width = imagesx($image);
$image_height = imagesy($image);

$text_bound = imageftbBox($font_size,$angle,$font,$text);

//Get the text upper,lower,left and right corner bounds
$lower_left_x =  $text_bound[0]; 
$lower_left_y =  $text_bound[1];
$lower_right_x = $text_bound[2];
$lower_right_y = $text_bound[3];
//$upper_right_x = $text_bound[4];
$upper_right_y = $text_bound[5];
//$upper_left_x =  $text_bound[6];
//$upper_left_y =  $text_bound[7];


//Get text Width and text height
$text_width =  $lower_right_x - $lower_left_x; //or  $upper_right_x - $upper_left_x
$text_height = $lower_right_y - $upper_right_y; //or  $lower_left_y - $upper_left_y

//Get the starting position for centering
$start_x_offset = ($image_width - $text_width) / 2;
$start_y_offset = ($image_height + $text_height) / 2;

// Add text to image
imagettftext($image,$font_size,$start_x_offset,$start_y_offset,$red,$text);


// Debug stats
$debug_text = "text_width:[" . $text_width . "]\n";
$debug_text .= "text_height:[" . $text_height . "]\n";
$debug_text .= "start_x_offset:[" . $start_x_offset . "]\n";
$debug_text .= "start_y_offset:[" . $start_y_offset . "]\n";
imagettftext($image,8,300,$white,$debug_text);


imagepng($image);
imagedestroy($image);

?>

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)