9

PHPを使用して画像にテキストを印刷するために書いています。ただし、関数imagettftext()はベースラインを使用しますが、テキストは垂直方向の中央に配置する必要があります。

したがって、上からベースラインまでの距離ではなく、バウンディングボックスの上から上までの距離で、yを使用してテキストを印刷する方法が必要です。または、バウンディングボックスの上部とベースラインの間の距離を決定できる方法が必要です。

どうやら、私はあなたを混乱させています。それで、明確にするために:私は関数を知っていますimagettfbbox()。その関数を使用して、結果のテキストボックスの高さと幅を決定できます。imagettftext()ただし、 Yパラメータはボックスの上部(または下部、少なくとも高さを使用して使用できたもの)までの距離ではなく、距離であるため、その高さは、で印刷する場合の垂直方向の位置合わせにはまったく役に立ちません。内のテキストのベースラインに。

編集:なぜ私は最新の答えを受け入れないのですか?

回答の下にある私の最新のコメントを参照し、この画像を参照として使用してください。

4

2 に答える 2

11

答えがまだ興味があるかどうかはわかりませんが、imagettfbbox()関数は、バウンディングボックスの高さと幅だけでなく、より多くの情報を提供します。imagettftext()が必要なテキストを管理するために必要な情報を返すように正確に設計されています。

秘訣は、imagettfbbox()から返される座標が絶対的な左上隅ではなく、特定のテキストのフォントのベースラインに関連しているという事実にあります。これが、ボックスがポイント座標で指定されており、これらが負であることが多いためです。

要するに:

$dims = imagettfbbox($fontsize, 0, $font, $text);

$ascent = abs($dims[7]);
$descent = abs($dims[1]);
$width = abs($dims[0])+abs($dims[2]);
$height = $ascent+$descent;

...

// In the example code, for the vertical centering of the text, consider
// the simple following formula

$y = (($imageHeight/2) - ($height/2)) + $ascent;

これは私のプロジェクトには完璧に機能します。この助けを願っています。

英語でごめんなさい。マルコ。

于 2013-02-21T11:30:34.040 に答える
5

あなたの質問が完全にはわかりません...例を挙げていただけますか?おそらくimagettfbboxはあなたが必要とするものですか?

// get bounding box dims
$dims = imagettfbbox($fontsize, 0, $font, $quote);

// do some math to find out the actual width and height
$width = $dims[4] - $dims[6]; // upper-right x minus upper-left x 
$height = $dims[3] - $dims[5]; // lower-right y minus upper-right y

編集:これは垂直方向に中央揃えされたテキストの例です

<?php
$font = 'arial.ttf';
$fontsize = 100;
$imageX = 500;
$imageY = 500;

// text
$text = "FOOBAR";

// create a bounding box for the text
$dims = imagettfbbox($fontsize, 0, $font, $text);

// height of bounding box (your text)
$bbox_height = $dims[3] - $dims[5]; // lower-right y minus upper-right y

// Create image
$image = imagecreatetruecolor($imageX,$imageY);

// background color
$bgcolor = imagecolorallocate($image, 0, 0, 0);

// text color
$fontcolor = imagecolorallocate($image, 255, 255, 255);

// fill in the background with the background color
imagefilledrectangle($image, 0, 0, $imageX, $imageY, $bgcolor);

$x = 0; 
$y = (($imageY/2) - ($bbox_height/2)) + $fontsize;
imagettftext($image, $fontsize, 0, $x, $y , $fontcolor, $font, $text);

// tell the browser that the content is an image
header('Content-type: image/png');
// output image to the browser
imagepng($image);

// delete the image resource 
imagedestroy($image);
?>
于 2011-07-18T18:44:02.333 に答える