Drawing Text


How about drawing text? There are a number of functions that draw text, such as imagestring:

 imagestring(resource image, int font, int x, int y, string s, int color) 

This function draws the string s in the image specified by image with the upper-left corner at coordinates x, y in color color. The graphics package comes with built-in fontsif font is 1, 2, 3, 4, or 5, a built-in font is used. Note that because we're working with graphics, this text is drawn as an image, not as the editable text that would appear in a text field.

Say for example that you want to display some text centered in an image. We'll use built-in font number 4 to show how that works. To center the text, you need the text's dimensions, which you can get with the imagefontwidth and imagefontheight functions. Here's how we determine the x and y positions at which to draw our text:

 $font_number = 4; $text = "No worries."; $width = 2 * strlen($text) * imagefontwidth($font_number); $height = 3 * imagefontheight($font_number); $image = imagecreate($width, $height); $back_color = imagecolorallocate($image, 200, 200, 200); $drawing_color = imagecolorallocate($image, 0,   0,   0); $x_position = ($width - (strlen($text) * imagefontwidth($font_number))) / 2; $y_position = ($height - imagefontheight($font_number)) / 2; 

Now that you have the x and y positions at which to draw the text, you can use imagestring to draw that text, as shown in phpdrawtext.php, Example 10.

Example 10. Drawing text, phpdrawtext.php
 <?php     $font_number = 4;     $text = "No worries.";     $width = 2 * strlen($text) * imagefontwidth($font_number);     $height = 3 * imagefontheight($font_number);     $image = imagecreate($width, $height);     $back_color = imagecolorallocate($image, 200, 200, 200);     $drawing_color = imagecolorallocate($image, 0,   0,   0);     $x_position = ($width - (strlen($text) * imagefontwidth($font_number)))/ 2;     $y_position = ($height - imagefontheight($font_number)) / 2;     imagestring($image, $font_number, $x_position, $y_position, $text,         $drawing_color);     header('Content-Type: image/jpeg');     imagejpeg($image);     imagedestroy($image); ?> 

We'll embed phpdrawtext.php in phpdrawtext.html this way:

 <HTML>     <HEAD>         <TITLE>Drawing text</TITLE>     </HEAD>     <BODY>         <CENTER>             <H1>                 Drawing text             </H1>             <BR>             <IMG src="/books/1/265/1/html/2/phpdrawtext.php">         </CENTER>     </BODY> </HTML> 

You can see the results in Figure 11. Very cool.

Figure 11. Drawing text.




    Spring Into PHP 5
    Spring Into PHP 5
    ISBN: 0131498622
    EAN: 2147483647
    Year: 2006
    Pages: 254

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net