note 40531 deleted from function.imagettfbbox by nlopess
| From: | nlopess@php.net | Date: | Sun, 07 Mar 2004 09:06:35 +0000 |
| Subject: | note 40531 deleted from function.imagettfbbox by nlopess | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-66383@lists.php.net to get a copy of this message | ||
Note Submitter: jrisken@mn.rr.com
----
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;
}
?>