How to determine the length (in pixels) of a string being rendered on a web page?
If I know the font size (12) and the font family (calibri), is there a way to determine the length (in pixels) a given string will take after it will be render开发者_如何学编程ed? I am absolutely certain about the font and size. Are there any lookup tables for this purpose to determine the length in PHP code itself? I am writing a PHP script to dynamically generate an SVG image which contains various boxes filled with data pulled out of a DB. The problem is that I need to manually wrap the text around and increase the size of the box if the string is big.
Thanks
Use the PHP function imagettfbbox
to get the size of the bounding box for the given string.
On the other hand you can use also javascript to manipulate SVG images in case you would like to handle it on the client side. That way it wouldn't even matter if the client had the specified font or not...
You could use PHP GD to render out the string as a image and get the size of the resulting image.
If you use this, it should work:
list($left,, $right) = imageftbbox( 12, 0, "arial.ttf", "Hello World");
$width = $right - $left;
Your title and actual post seem to say slightly different things. I'm guessing what you're really asking is whether it's possible to determine the width in pixels of text rendered on a web page in your PHP code (prior to web page being rendered).
If so, the answer is "NO". Said font may not be available on user's computer; s/he may have custom stylesheet applied; use large font sizes; etc...
What you can do is determine that width using javascript after the page is rendered (obviously, you can do that in some other page as well and hope nothing changes till then) and submit that back to PHP. With some clever AJAX-ing you can even do this on the same page.
Take a look at this question for details on how to do this in javascript.
Use jQuery,
$("text").each(function(){alert(this.innerHTML+" is "+$(this).width()+" pixels.");});
If you want to determine the string length of text, using PHP's Build-In-Fonts (e.g. if you are using imagestring()), you can use:
imagefontwidth()
$text = "Your text here"
$fontSize = 5;
$textLength = imagefontwidth($fontSize) * strlen($text);
If you do not use the Build-In-Fonts, use imagettfbbox(), like mentioned above.
精彩评论