note 40531 added to function.imagettfbbox
| From: | jrisken at mn dot rr dot com | Date: | Sat, 06 Mar 2004 21:45:16 +0000 |
| Subject: | note 40531 added to function.imagettfbbox | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-66360@lists.php.net to get a copy of this message | ||
I took Magicaltux's word wrap procedure and modified it in two ways. I changed the order of
processing so that the string plotting function is called only once for each word instead of for
every character. And I wrote the results to a string scalar instead of a string array, with
embedded breaks <br> at line ends. It should run pretty fast. Mine breaks only on spaces,
but hyphens could easily be added.
I'm new to PHP so I apologize for my idiosyncratic formatting conventions.
function myWordWrap($txt,$font,$size,$width)
{
/*
word-wrapper. gets bounding box sizes for each word in a string, then
strings words together up to desired width. calls strpos and
imagettfbbox only once per word - so very fast.
this version reconcatenates the words with a <br> character where
the line break should be.
*/
$txt.=" "; // guaranteed to find end of line
$spaces=array();
$wids=array();
$i=0;
while(true)
{
$j=strpos(substr($txt,$i)," ");
if(!($j===false))
{
$spaces[]=$j+$i;
$bbox=imagettfbbox($size,0,$font,substr($txt,$i,$j+1));
$left=($bbox[0]>$bbox[6])?$bbox[6]:$bbox[0];
$right=($bbox[2]>$bbox[4])?$bbox[2]:$bbox[4];
$wids[]=$right-$left;
$i=$j+$i+1;
}
else break;
}
$lastspace=-1;
$cum=0;
$t2="";
for($i=0;$i<count($spaces);$i++)
{
if((($cum>0)&&($cum+$wids[$i])>$width)) // time for a line break
{
$t2.="<br>";
$cum=0;
$i--;
}
else
{
// we'll always get at least one word (even if too wide) thanks to
// ($cum>0) test above
$t2.=substr($txt,$lastspace+1,$spaces[$i]-$lastspace);
$cum+=$wids[$i];
$lastspace=$spaces[$i];
}
}
return $t2;
}
?>
----
Manual Page -- http://www.php.net/manual/en/function.imagettfbbox.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+40531
Delete -- http://master.php.net/manage/user-notes.php?action=delete+40531&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+40531&report=yes
Search -- http://master.php.net/manage/user-notes.php