Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Do it like this. Remember to place the font file "arial.ttf" in current directory:</p> <pre><code>&lt;?php // Create a 650x150 image and create two colors $im = imagecreatetruecolor(650, 150); $white = imagecolorallocate($im, 255, 255, 255); $black = imagecolorallocate($im, 0, 0, 0); // Set the background to be white imagefilledrectangle($im, 0, 0, 649, 149, $white); // Path to our font file $font = './arial.ttf'; //test it out for($i=2;$i&lt;10;$i++) WriteTextForMe($im, $font, str_repeat($i, $i), -140 + ($i*80), 70 + rand(-30, 30), -160 + (($i+1)*80), 150, $black); //this function does the magic function WriteTextForMe($im, $font, $text, $x1, $y1, $x2, $y2, $allocatedcolor) { //draw bars imagesetthickness($im, 2); imagerectangle($im, $x1, $y1, $x2, $y2, imagecolorallocate($im, 100,100,100)); //draw text with dynamic stretching $maxwidth = $x2 - $x1; for($size = 1; true; $size+=1) { $bbox = imagettfbbox($size, 0, $font, $text); $width = $bbox[2] - $bbox[0]; if($width - $maxwidth &gt; 0) { $drawsize = $size - 1; $drawX = $x1 + $lastdifference / 2; break; } $lastdifference = $maxwidth - $width; } $size--; imagettftext($im, $drawsize, 0, $drawX, $y1 - 2, $allocatedcolor, $font, $text); } // Output to browser header('Content-type: image/png'); imagepng($im); imagedestroy($im); ?&gt; </code></pre> <p>It uses <code>imagettfbbox</code> function to get width of the text, then loops over the font size to get correct size, centers it and displays it.</p> <p><strong>So, it outputs the following:</strong></p> <p><img src="https://i.stack.imgur.com/6kLA1.png" alt="alt text"></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload