PHP GD ttftext center alignment

后端 未结 2 965
萌比男神i
萌比男神i 2021-02-06 11:33

I\'m using imagettftext to make a bar graph and at the top of each bar I want to put the value.

I have the fol

2条回答
  •  别那么骄傲
    2021-02-06 12:02

    You can calculate the center of your text by using PHP's imagettfbbox-function:

    // define text and font
    $text = 'some bar label';
    $font = 'path/to/some/font.ttf';
    
    // calculate text size (this needs to be adjusted to suit your needs)
    $size = 10 / (strlen($text) * 0.1);
    
    // calculate bar center
    $barCenter = $x1 + ($x2 - $x1) / 2;
    
    // calculate text position (centered)
    $bbox = imagettfbbox($size, 0, $font, $text);
    $textWidth = $bbox[2] - $bbox[0];
    $positionX = $textWidth / 2 + $barCenter;
    $positionY = $y1 - $size;
    

    EDIT: Updated the code to do all the work for you.

提交回复
热议问题