2

I have noticed that when using 'imagettfbbox' it seems to be far from accurate. For example:

<?php
$text = 'hello there';
$box = imagettfbbox(12,0,'arial.ttf',$text);
$width = abs($box[0]-$box[2]);
$text = str_replace(' ','&nbsp;',$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;
?>

As you can see here, the box almost completely cuts off the 'e'. Is there any other solution to getting an accurate box width?

Robbie
  • 700
  • 2
  • 6
  • 18

1 Answers1

1

There could be a couple of things going on here. First is that you're not telling the browser to use the same font-set as your PHP is. While this is unlikely to be a problem with such a common font like arial, it's something you might want to double check. Use this css to tell the browser to use your font.

@font-face {
  font-family: "arial";
  src: url("arial.ttf");
}

The other problem is that you're not perfectly aligning your yellow box to the text on the left side. PHP's imagettfbbox is measuring your text exactly so any offset will give the appearance of a problem. Here's the html I used to test.

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

It aligned perfectly left to right for me. I would suggest that this isn't a problem with imagettfbbox, and you've just got to play around with some things to confirm that on your end.

OffTheBricks
  • 425
  • 2
  • 9
  • Actually looking through the php feedback this apparently has been a known problem for 6 years with the no solution presented. So I guess this is just one of the SOL problems. – Robbie Feb 24 '16 at 22:48