菜单

imagettftext字符间距

2010年09月16日 - php

imagepstext有字符间距参数,而imagettftext没有,解决思路是逐个写入字符,有两种方法
方法1.效果较好
$STRING = “This is a font test!”;

// —- PRESETS
$FONT = “demo.TTF”;
$FONT_SIZE = 12;
$WIDTH = 786;
$HEIGHT = 22;
$KERNING = 12;
$BASELINE = 17;
$BG_COLOR = array(
“R”=>255,
“G”=>213,
“B”=>0
);
$TXT_COLOR = array(
“R”=>0,
“G”=>96,
“B”=>161
);

// —- CREATE CANVAS + PALETTE
$canvas = imageCreateTrueColor($WIDTH*4,$HEIGHT*4);

$bg_color = imageColorAllocate($canvas, $BG_COLOR[“R”], $BG_COLOR[“G”], $BG_COLOR[“B”]);

$txt_color = imageColorAllocate($canvas, $TXT_COLOR[“R”], $TXT_COLOR[“G”], $TXT_COLOR[“B”]);

imagefill ( $canvas, 0, 0, $bg_color );

// —- DRAW

$array = str_split($STRING);
$hpos = 13*4;

for($i=0; $i<count($array); $i++)
{
$bbox = imagettftext( $canvas, $FONT_SIZE*4, 0, $hpos, $BASELINE*4, $txt_color, $FONT, $array[$i] );
$hpos = $bbox[2] + $KERNING;
}
// —- SAMPLE DOWN & OUTPUT
$final = imageCreateTrueColor($WIDTH,$HEIGHT);
imageCopyResampled( $final, $canvas, 0,0,0,0, $WIDTH, $HEIGHT, $WIDTH*4, $HEIGHT*4 );
header(‘Content-type: image/gif’);
imagegif($final);
imageDestroy($canvas);
imageDestroy($final);

方法2.
header(“Content-type: image/gif”);
$im = @imagecreate (786, 22) or die (“Cannot Initialize new GD image stream”);
$fontsize = 12;
$background = imagecolorallocate($im, 255, 213, 0);
//background image , notice: format eq.
//$im = imagecreatefromjpeg(‘/www/images/demo/1.jpg’);
$font_color = ImageColorAllocate ($im, 0, 96, 161); //font color
$font_file = “demo.TTF”;               //path
//font size, 0 is corner, 10,36 is position
$text = “This is a  font test!”;
//$text = “adfasfewbdfshrthnsvsvsdfg erege gw gwer gwe gr”;
$pval = ”;
for($i=0;$i<strlen($text);$i++){
// Get single character
$value=substr($text,$i,1);
if($pval){ // check for existing previous character
list($lx,$ly,$rx,$ry) = imagettfbbox($fontsize,0,$font_file,$pval);
$nxpos+=$rx+4;
}else{
$nxpos=13;
}
// Add the letter to the image
imagettftext($im, $fontsize, 0, $nxpos, 17, $font_color, $font_file, $value);
$pval=$value; // save current character for next loop
}
//imagettftext($im, 12, 0, 13, 18, $font_color ,$font_file, $text);  //insert words
imagegif ($im);
// clean up
ImageDestroy($im);

发表评论

电子邮件地址不会被公开。 必填项已用*标注