本文实例讲述了PHP实现在限定区域里自动调整字体大小的类。分享给大家供大家参考。具体如下:
这里的PHP类imagefittext.class.PHP实现在限定的区域里自动调整字体大小的功能。
PHP;">
font = $font;
$this->step_wrap = $step_wrap>1?$step_wrap:1;
$this->step_fontsize = $step_fontsize>1?$step_fontsize:1;
}
function fit($width,$height,$text,$min_fontsize=5,$min_wraplength=0){
$this->fontsize = & $fontsize;
$text_ = $text;
while($this->TextHeight($text_)>$height && $fontsize>$min_fontsize)
$fontsize -= $this->step_fontsize;
while(($this->TextWidth($text_)>$width || $this->TextHeight($text_)>$height) && $fontsize>$min_fontsize){
$fontsize -= $this->step_fontsize;
$wraplength = $this->maxLen($text);
$text_ = $text;
while($this->TextWidth($text_)>$width && $wraplength>=$min_wraplength+$this->step_wrap){
$wraplength -= $this->step_wrap;
$text_ = wordwrap($text,$wraplength,"\n",true);
//To speed up:
if($this->TextHeight($text_)>$height) break;
if($wraplength<=$min_wraplength) break;
$wraplength_ = $wraplength;
$wraplength = ceil($wraplength/($this->TextWidth($text_)/$width));
$wraplength = $wraplength<($min_wraplength+$this->step_wrap)?($min_wraplength+$this->step_wrap):$wraplength;
}
}
$this->width = $this->TextWidth($text_);
$this->height = $this->TextHeight($text_);
return array("fontsize"=>$fontsize,"text"=>$text_,"width"=>$this->width,"height"=>$this->height);
}
function maxLen($text){
$lines = explode("\n",str_replace("\r","",$text));
foreach($lines as $line)
$t[] = strlen($line);
return max($t);
}
function TextWidth($text){
$t = imagettfbBox($this->fontsize,$this->font,$text);
return $t[2]-$t[0];
}
function TextHeight($text){
$t = imagettfbBox($this->fontsize,$text);
return $t[1]-$t[7];
}
}
?>
使用范例如下:
PHP;">
fit($width-$padding*2,$height-$padding*2,$min_fontsize,$min_wraplength);
// Stop the timer
$time = round(microtime_float()-$time_start,3);
$white = imagecolorallocate($im,255,255);
// Draw a Box
imagerectangle($im,$x1,$y1,$x1+$width,$y1+$height,$white);
// Write the text +8 because the text will move up originally
imagettftext($im,$fit['fontsize'],$x1+$padding,$y1+$padding+8,$white,$font,$fit['text']);
// Print some info. about the text
imagestring($im,5,$y1+$height+30,'Fontsize : '.$fit['fontsize'],$white);
imagestring($im,$y1+$height+45,'Text Size : '.$fit['width']."x".$fit['height'],$y1+$height+60,'Box Size : '.($width-$padding*2)."x".($height-$padding*2),$y1+$height+75,'Time used : '.$time.'s',$white);
// Print the image
header ('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
function microtime_float(){ // Timer
list($usec,$sec) = explode(" ",microtime());
return ((float)$usec + (float)$sec);
}
?>
希望本文所述对大家的PHP程序设计有所帮助。