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 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler