0

I have a proplem.

How can I set the size automatically with text When I change the font size and text space

$font = 'Helvetica.ttf';
$text ='Test';
$size = '12';
//-------------------------++
$im = imagecreatetruecolor(150, 25);
$color = imagecolorallocate($im, 119,119,119); //http://www.color-hex.com/color/777777
$transparent = imageColorAllocateAlpha($im, 0, 0, 0, 127);
//-------------------------++
imageSaveAlpha($im, true);
imageAlphaBlending($im, false);
imagefilledrectangle($im, 0, 0, 399, 29, $transparent);
imageAlphaBlending($im, true);
//-------------------------++
$bbox = imagettfbbox($size, 0, $font, $text);
$dx = ($bbox[2]-$bbox[0])/2.0 - ($bbox[2]-$bbox[4])/2.0;
$dy = ($bbox[3]-$bbox[1])/2.0 + ($bbox[7]-$bbox[1])/2.0;
$x = 0;
$y = 0;
$px = $x-$dx;
$py = $y-$dy;
//-------------------------++
imagettftext($im, $size, 0, $px, $py, $color, $font, $text);
//-------------------------++
header('Content-Type: image/png');
imagePng($im);
imageDestroy($im);

Problems at the location of the text! enter image description here

3
  • exactly as you are: imagettfbbox() so you can tell what size the rendered text will be. you just need to adjust your coordinates properly.
    – Marc B
    Apr 10, 2015 at 16:50
  • I don't see where $x and $y are set in your script. So they become 0. So you $px and $py values become negative values. Is that the expected value?
    – Twisty
    Apr 10, 2015 at 16:52
  • How adjust coordinates properly.
    – J7xx
    Apr 10, 2015 at 16:54

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.