Web Directory - Balance Transfer Credit Cards - Online Advertising - Submit article - Wordpress Themes

PDA

View Full Version : Calculating string length for use in image


Cobnut
Feb 29th 2008, 9:42 am
I'm building a simple graphing function and would like to include some labels within the bars of the graph; like this:

http://www.cobnut.net/examples/chart.jpg

I've got tests for the width of the bars that increases/decreases the font number (or doesn't show text at all) but I need some way to limit the length of the text dependent upon the size of the bar itself. Ideally, I'd like to be able to say 'if the text gets within x pixels of the top of the bar, then substr it down to a point where it's within the bar'. As it happens, for this particular project I can be fairly certain that the bars are always going to be around 75% of the chart but I can't control the label text itself and some could be longer than those shown on the example.

I suppose what I'm after is some direct equation between the standard font number in imagestring and the 'size' per character.

Anyone have any ideas?

Jon

RoscoeT
Mar 1st 2008, 12:26 am
I think you should likely do this with CSS rather than in your php code. Font size and pixel size vary from machine to machine.

stoli
Mar 1st 2008, 3:44 am
The imagefontwidth function should give you what you want:
http://www.php.net/manual/en/function.imagefontwidth.php

Here is a way you could use it to truncate a string to fit in a given image:
<?php

$text = "Pack my box with five dozen liquor jugs";
$font = 3; // font size
$outputimage = 1; // 1 to output image, 0 to output text

// create a 140*30 image
$imgwidth = 140;
$imgheight = 30;
$im = imagecreate($imgwidth, $imgheight);

// blue background and white text
$bg = imagecolorallocate($im, 0, 0, 255);
$textcolor = imagecolorallocate($im, 255, 255, 255);

// limit font range
if ($font < 0 || $font > 5) $font = 0;

// truncate the text to fit the image width
$width = strlen($text) * imagefontwidth($font);
while ($width > $imgwidth) {
$text = substr($text, 0, -1);
$width = strlen($text) * imagefontwidth($font);
}

// write the string at the top left of image
imagestring($im, $font, 0, 0, $text, $textcolor);

// output the image
if ($outputimage) {
header("Content-type: image/png");
imagepng($im);
} else {
echo $text;
}

?>

Try it with different font sizes, either outputting the text or image to see how it works.