php GD库文字居中,PHP GD ttftext居中对齐

这样做。请记住字体文件“ARIAL.TTF”放置在当前目录下:

// Create a 650x150 image and create two colors

$im = imagecreatetruecolor(650, 150);

$white = imagecolorallocate($im, 255, 255, 255);

$black = imagecolorallocate($im, 0, 0, 0);

// Set the background to be white

imagefilledrectangle($im, 0, 0, 649, 149, $white);

// Path to our font file

$font = './arial.ttf';

//test it out

for($i=2;$i<10;$i++)

WriteTextForMe($im, $font, str_repeat($i, $i), -140 + ($i*80), 70 + rand(-30, 30), -160 + (($i+1)*80), 150, $black);

//this function does the magic

function WriteTextForMe($im, $font, $text, $x1, $y1, $x2, $y2, $allocatedcolor)

{

//draw bars

imagesetthickness($im, 2);

imagerectangle($im, $x1, $y1, $x2, $y2, imagecolorallocate($im, 100,100,100));

//draw text with dynamic stretching

$maxwidth = $x2 - $x1;

for($size = 1; true; $size+=1)

{

$bbox = imagettfbbox($size, 0, $font, $text);

$width = $bbox[2] - $bbox[0];

if($width - $maxwidth > 0)

{

$drawsize = $size - 1;

$drawX = $x1 + $lastdifference/2;

break;

}

$lastdifference = $maxwidth - $width;

}

$size--;

imagettftext($im, $drawsize, 0, $drawX, $y1 - 2, $allocatedcolor, $font, $text);

}

// Output to browser

header('Content-type: image/png');

imagepng($im);

imagedestroy($im);

?>

它使用imagettfbbox函数来获取文本的宽度,然后循环在字体大小以获得正确的大小,其中心并显示它。

因此,它输出以下:

5a63fc7f5b7542dd154182b0f21a1f34.png

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值