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 关于大棚监测的pcb板设计
  • ¥20 sim800c模块 at指令及平台
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计