15.4. Drawing Text
Problem
You want to draw text as a graphic. This allows you to make dynamic buttons or hit counters.
Solution
For
built-in GD
fonts, use ImageString( )
:
ImageString($image, 1, $x, $y, 'I love PHP Cookbook', $text_color);
For
TrueType
fonts, use ImageTTFText( )
:
ImageTTFText($image, $size, 0, $x, $y, $text_color, '/path/to/font.ttf', 'I love PHP Cookbook');
For
PostScript Type 1 fonts, use
ImagePSLoadFont( )
and ImagePSText( )
:
$font = ImagePSLoadFont('/path/to/font.pfb'); ImagePSText($image, 'I love PHP Cookbook', $font, $size, $text_color, $background_color, $x, $y);
Discussion
Call ImageString( )
to place text onto the canvas.
Like other GD drawing functions, ImageString( )
needs many inputs: the image to draw on, the font number, the x and y
coordinates of the upper right position of the first characters, the
text string to display, and finally, the color to use to draw the
string.
With ImageString( )
, there are five possible font
choices, from 1 to 5. Font number 1 is the smallest, while font 5 is
the largest, as shown in Figure 15-5. Anything above
or below that range generates a size equivalent to the closest legal
number.
Figure 15-5. Built-in GD font sizes
To draw text vertically instead of
horizontally, use the function ImageStringUp( )
instead. Figure 15-6 shows the output.
ImageStringUp($image, 1, $x, $y, 'I love PHP Cookbook', $text_color);
Figure 15-6. Vertical ...
Get PHP Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.