2014-03-06 73 views
1

我的目標是繪製水平居中的m。因此,我計算字母的寬度,從總寬度中減去該值,最後除以2.結果應該是從左邊開始的距離(或者等於從右邊開始)。無法以GD2水平居中'm'

但是,'米'總是錯位。我也注意到一些字體可能不會觸發有問題的行爲。請注意,我的腳本正確地適用於所有其他拉丁字符。

宋體:

Misplaced 'm'; font: Arial

碼流維拉三世:

Misplaced 'm'; font: Bitstream Vera Sans

<?php 

$totalWidth = 100; 
$totalHeight = 100; 
$font = 'Arial.ttf'; 

$img = imagecreatetruecolor($totalWidth, $totalHeight); 
$red = imagecolorallocate($img, 255, 0, 0); 

$fontSize = 100; 
$bbox = imagettfbbox($fontSize, 0, $font, 'm'); 
$width = max($bbox[2], $bbox[4]) - max($bbox[0], $bbox[6]); 

$centeredX = ($totalWidth - $width)/2; 

imagettftext($img, 100, 0, $centeredX, 100, $red, $font, 'm'); 
imagepng($img, 'testcase.png'); 
imagedestroy($img); 

回答

2

裏還剩下每個字母的小空間,這是不同的每個字母。 PHP.net上的某人爲此寫了一個解決方案:http://www.php.net/manual/en/function.imagettfbbox.php#97357

您需要稍微調整一下代碼。

$totalWidth = 100; 
$totalHeight = 100; 
$font = 'Arial.ttf'; 

// change letter to see it with different letters 
$letter = "m"; 

$img = imagecreatetruecolor($totalWidth, $totalHeight); 
$red = imagecolorallocate($img, 255, 0, 0); 

$fontSize = 100; 
$bbox = calculateTextBox($fontSize, 0, $font, $letter); 

$centeredX = (($totalWidth - $bbox['width'])/2); 

// here left coordinate is subtracted (+ negative value) from centeredX 
imagettftext($img, 100, 0, $centeredX + $bbox['left'], 100, $red, $font, $letter); 

header('Content-Type: image/png'); 
imagepng($img); 
imagedestroy($img); 
+0

完美答案!非常感謝你!我也設法垂直居中:''centeredY =(($ totalHeight - $ bbox ['height'])/ 2);'和'$ centeredY + $ bbox ['top']'作爲imagettftext的Y參數()'。 – ComFreek