我注意到使用' imagettfbbox'它似乎远非准确。 例如:
<?php
$text = 'hello there';
$box = imagettfbbox(12,0,'arial.ttf',$text);
$width = abs($box[0]-$box[2]);
$text = str_replace(' ',' ',$text);
echo '<svg width="500" height="200">
<g transform="scale(5)">
<text x="0" y="20" style="font-family:arial; font-size:12pt;">'.$text.'</text>
<rect x="0" y="10" width="'.$width.'" height="20" style="fill-opacity:0.5; fill:yellow;" />
</g>
</svg>';
exit;
?>
正如你在这里看到的那样,盒子几乎完全切断了“e”。 有没有其他解决方案来获得准确的盒子宽度?
答案 0 :(得分:1)
这里可能会发生一些事情。首先,您并没有告诉浏览器使用与PHP相同的字体集。虽然这对像arial这样的常见字体来说不太可能有问题,但您可能需要仔细检查。使用此css告诉浏览器使用您的字体。
@font-face {
font-family: "arial";
src: url("arial.ttf");
}
另一个问题是,您没有将黄色框与左侧的文字完美对齐。 PHP的imagettfbbox正在精确测量您的文本,因此任何偏移都会出现问题。这是我以前测试的html。
<div style="position:relative;">
<div style="font-family:arial; font-size:12pt; position: absolute; left: 0px;"><?php echo $text;?></div>
<div style="width:<?php echo $width;?>px;height:20px;position:absolute;left:1px;background-color:yellow;opacity:0.5;"/>
</div>
它完美地从左到右对齐。我建议这对imagettfbbox来说不是一个问题,你只需要做一些事情来确认你的结果。