PHP imagettftext return bounding box differs from rendered bounding box

半城伤御伤魂 提交于 2019-12-24 03:16:34

问题


I'm using imagettftext to render a PNG file. A call to imagettftext() returns the bounding box that the text was rendered in, but on closer inspection, the text is being rendered slightly outside of it's own bounding box! The bounding box is correct (I inspected the pixel coords of the image), but the text location is incorrect, it outputs this, where the box is the returned bounding box after rendering the text:

My code is:

// helper function for geting textbox bounds
function bounds($text,$fontFile,$fontSize,$fontAngle) { 
    $rect = imagettfbbox($fontSize,$fontAngle,$fontFile,$text); 
    $minX = min(array($rect[0],$rect[2],$rect[4],$rect[6])); 
    $maxX = max(array($rect[0],$rect[2],$rect[4],$rect[6])); 
    $minY = min(array($rect[1],$rect[3],$rect[5],$rect[7])); 
    $maxY = max(array($rect[1],$rect[3],$rect[5],$rect[7])); 

    return array( 
        "left"   => abs($minX) - 1, 
        "top"    => abs($minY) - 1, 
        "width"  => $maxX - $minX, 
        "height" => $maxY - $minY, 
        "box"    => $rect 
    ); 
}

$canvas = @imagecreate(640, 680)
    or die('Cannot Initialize new GD image stream');

$title_color = imagecolorallocate($canvas, 153, 153, 153);
$content_color = imagecolorallocate($canvas, 51, 51, 51);

$content_bounds = bounds("12", "Helvetica_Reg.ttf", 75, 0);
$test = imagettftext($canvas, 75, 0, 30, 200, $content_color, "Helvetica_Reg.ttf", "12");
imagerectangle($canvas, $test[0], $test[1], $test[4], $test[5], $title_color);

回答1:


maybe is a problem with the font, i test your code with another one, and i got



来源:https://stackoverflow.com/questions/24958337/php-imagettftext-return-bounding-box-differs-from-rendered-bounding-box

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!