【问题标题】:imagestring - Get the size of the string lengh in pixelsimagestring - 获取字符串长度的大小(以像素为单位)
【发布时间】:2015-03-05 19:45:50
【问题描述】:

你好, 只是想提前提一下,这不是重复的。 我已经看过类似的帖子,但所有这些都使用特定的字体,但情况并非如此。 我正在使用默认字体号 3(对于本示例),我希望能够计算输出大小并将其放在 $canvas 的确切中心

imagestring($canvas,3,imagesx($canvas),imagesy($canvas),$myString,imagecolorallocate($canvas,239,13,177));

我知道如何进行计算以将其置于中心位置,这很容易,唯一遗漏的参数是考虑到字体号 3 的字符串的确切大小(以像素 (x/y) 为单位)。 考虑到字体号 3,我的字符串的像素 (x/y)。

【问题讨论】:

    标签: php image canvas png pixels


    【解决方案1】:

    在不使用特定字体的情况下更新了答案。 PHP 嵌入的字体确实是等宽的(经过测试并且可以工作):

    $font           = 3;
    $img            = imagecreatetruecolor(500, 500);
    $text           = "Waldson Patricio";
    $color          = imagecolorallocate($img, 255, 255, 255);
    $size           = strlen($text);
    
    $tw             = $size * imagefontwidth($font);
    $th             = imagefontheight($font);
    
    
    
    imagestring($img, $font, (imagesx($img) - $tw) / 2 , (imagesy($img) - $th) / 2, $text, $color);
    header('Content-type:image/jpeg');
    imagejpeg($img);
    

    【讨论】:

    • 完美男人!非常感谢! (你的代码还有一个小错误,但我修复了它:)
    【解决方案2】:

    imagettfbboximagettftext 将完成这项工作:

    //setup
    $font     = '<path to font>';
    $string   = 'My String';
    $fontSize = 12;
    
    //getting width and height
    $bBox   = imagettfbbox($fontSize, 0, $font, $string);
    $width  = $bBox[2] - $bBox[0];
    $height = $bBox[1] - $bBox[7];
    
    //drawing in the center
    imagettftext($canvas, $fontSize, 0, (imagesx($canvas) - $width)/2, (imagesy($canvas) - $height)/2, $color, $font, $string);
    

    【讨论】:

    • 我做了...不是很有帮助
    • 如果你从右下X减去左下X,你会得到字符串的宽度。如果用左下 Y 减去左上 Y,就得到高度。
    • 我已经看到了,但@Walsdon 假设我使用了一种特殊的字体,而这里不是这种情况......
    • 好吧,我不打算使用特定的字体,但是因为它可以工作(除非你有一个错误并且需要将 $text 更改为 $string ;)...我将使用这个示例!谢谢你!
    【解决方案3】:

    经过一番研究,我找不到图像字符串中使用的字体具有标准宽度或间距。在我的 PHP 实现中,字体 3 似乎有 6 x 9 像素字符,1 像素间距,等宽,所以 7 * strlen 应该给出一个非常准确的宽度,而 9 应该给出高度(我假设你只使用居中一个行)的字符串图像。但是,这可能是特定于平台或实现的,所以如果它不适合您,您必须自己衡量。

    如果你必须使用 imagestring(),当然是这个解决方案 -- 正如 Waldson 建议的那样,使用 imagettftext() 和 imagettfbbox() 会更好地进行精确测量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-28
      • 2012-10-31
      • 2013-06-17
      • 2016-06-16
      • 1970-01-01
      • 2014-07-16
      相关资源
      最近更新 更多