2009-11-15 58 views
4

我试图通过使用标题的自定义字体来激发我的网站。对我来说,最合适的方法是使用PHP和GD。我已经写了一个脚本,它将根据$ _GET值输出动态文本,但是有时图像太宽,会移动其他所有内容。动态GD图像宽度文本

如何根据文字宽度调整图像的宽度?以下是我迄今为止编写的代码:

<?php 
// Settings 
$sText = $_GET['t']; // Text of heading 
$sFont = "font/AvantGarde-Book.ttf"; // Default font for headings 
$sMain = $_GET['c'] ? $_GET['c'] : 0xF2AB27; // Get a font or default it 

// Create the image 
header("content-type: image/png"); // Set the content-type 
$hImage = imagecreatetruecolor(200, 24); 
ImageFill($hImage, 0, 0, IMG_COLOR_TRANSPARENT); 
imagesavealpha($hImage, true); 
imagealphablending($hImage, false); 
imagettftext($hImage, 20, 0, 0, 24, $sMain, $sFont, $sText); // Draw the text 
imagepng($hImage); // Generate the image 
imagedestroy($hImage); // Destroy it from the cache ?> 

谢谢!

回答

6

好吧,我想通了!对于其他人谁可能有这个问题,你需要添加:

// Calcuate the width of the image 
$arSize = imagettfbbox(24, 0, $sFont, $sText); 
$iWidth = abs($arSize[2] - $arSize[0]); 
$iHeight = abs($arSize[7] - $arSize[1]); 

的imagecreatetruecolor()之前

4

函数imagettfbbox将根据您选择的字体计算文本大小。在调用imagecreatetruecolor的过程中使用结果。

+0

我似乎无法得到这个工作,它要么打破了图像或导致错误? – 2009-11-15 17:26:34