dreamfly0514 2014-06-11 11:22
浏览 41
已采纳

PHP imagettftext,中心动态文本

I`m working on a script that posts tweets to twitter with a random generated image with a random background color. Thats working perfectly but I want to show the rgb colors in the center of the image but its not working right. This is my code:

$rgbColor = array(rand(0,255),rand(0,255),rand(0,255));
$image = imagecreatetruecolor(600, 200);
$color = imagecolorallocate($image, $rgbColor[0], $rgbColor[1], $rgbColor[2]);
$white = imagecolorallocate($image, 255, 255, 255);
$black = imagecolorallocate($image, 0, 0, 0);
imagefill($image, 0, 0, $color);
imagettftext($image, 20, 0,(300-(strlen('rgb('.$rgbColor[0].', '.$rgbColor[1].', '.$rgbColor[2].')')*20)/2), 75, (brghtdiff($rgbColor[0], $rgbColor[1], $rgbColor[2]) > 125 ? $black : $white), './Station.ttf', 'rgb('.$rgbColor[0].', '.$rgbColor[1].', '.$rgbColor[2].')');
imagejpeg($image, './image.jpg');
imagedestroy($image);

Creates:

preview

Well, it displays the rgb(int, int, int) not in the center, does anyone know how the text can be in the center?

  • 写回答

2条回答 默认 最新

  • douguanya6399 2014-06-11 11:39
    关注

    You are trying to determine the width of your text basing on its length multiplied by 20. This approach isn't correct because not all characters in your string have width of 20 pixels.

    You should use imagettfbbox() function which will return array containing coordinates of corners of bounding box of your text. Basing on its result you can count real width of your text and position it correctly.

    $bbox = imagettfbbox(20, 0, './Station.ttf', 'rgb('.$rgbColor[0].', '.$rgbColor[1].', '.$rgbColor[2].')');
    
    $x = 300 - ($bbox[4] / 2);
    
    imagettftext($image, 20, 0, $x, 75, (brghtdiff($rgbColor[0], $rgbColor[1], $rgbColor[2]) > 125 ? $black : $white), './Station.ttf', 'rgb('.$rgbColor[0].', '.$rgbColor[1].', '.$rgbColor[2].')');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 换yum源但仍然用不了httpd
  • ¥50 C# 使用DEVMOD设置打印机首选项
  • ¥15 麒麟V10 arm安装gdal
  • ¥15 想用@vueuse 把项目动态改成深色主题,localStorge里面的vueuse-color-scheme一开始就给我改成了dark,不知道什么原因(相关搜索:背景颜色)
  • ¥20 OPENVPN连接问题
  • ¥15 flask实现搜索框访问数据库
  • ¥15 mrk3399刷完安卓11后投屏调试只能显示一个设备
  • ¥100 如何用js写一个游戏云存档
  • ¥15 ansys fluent计算闪退
  • ¥15 有关wireshark抓包的问题