2016-06-17 20 views
0

imagettftextを使用してPHPで作成した画像のテキストを中央に配置する方法がわかりません。ここに私のコードは次のとおりです。ここでPHPの画像の中央揃え

header('Content-Type: image/png'); 
$im = imagecreatetruecolor(260, 180); 
$background = imagecolorallocate($im, 0, 0, 255); 
$white = imagecolorallocate($im, 255, 255, 255); 
$grey = imagecolorallocate($im, 60, 153, 181); 
$black = imagecolorallocate($im, 0, 0, 0); 
imagefilledrectangle($im, 0, 0, 399, 200, $white); 
$text = $_GET['tname']; 
$font = 'OpenSans-Semibold.ttf'; 
imagettftext($im, 20, 0, $x+1, $y+1, $grey, $font, $text); 
imagettftext($im, 20, 0, $x, $y, $black, $font, $text); 
imagepng($im); 
imagedestroy($im); 
+0

[imagetttfbbox](http://php.net/manual/en/function.imagettfbbox.php)を使用しますあなたのテキストがどれほど大きいかを知るためには、イメージ内のどこにボックスを置くべきかを計算することが必要です。 –

+0

私に事例を教えてもらえますか?私はドキュメントを読んでみましたが、返された結果についての部分は本当に分かりませんでした。 – icecreamscoop

答えて

1

imagetttfbboxに基づいて、実施例である:

$im = imagecreatetruecolor(200, 75); 
$white = imagecolorallocate($im, 255, 255, 255); 
$black = imagecolorallocate($im, 0, 0, 0); 

// text, font and size to draw 
$text = 'hello world'; 
$font = 'OpenSans-Semibold.ttf'; 
$size = 30; 

// determine the size of the text so we can center it 
$box = imagettfbbox($size, 0, $font, $text); 
$text_width = abs($box[2]) - abs($box[0]); 
$text_height = abs($box[5]) - abs($box[3]); 
$image_width = imagesx($im); 
$image_height = imagesy($im); 
$x = ($image_width - $text_width)/2; 
$y = ($image_height + $text_height)/2; 

// add text 
imagettftext($im, $size, 0, $x, $y, $white, $font, $text); 

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

// output and destroy image 
imagepng($im); 
imagedestroy($im); 
+0

ありがとう、遅い返事をおかけして申し訳ありません。 – icecreamscoop

関連する問題