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 回答