18.13 Dynamic Buttons
TechniqueThis code will create dynamic buttons on-the-fly , given some text and a background image. This saves time if you want to have constantly changing text on images and you don't feel like using Photoshop or GIMP to make each button: The variables : vars.php The code: <?php // // The color of the text to be drawn can be either 'r' (red), // 'g' (green), 'bl' (blue), 'b' (black), 'w' (white). // $txtCol = "w"; // // The Font size of the number, can be from 1 .. 5 // $defaultFont = 4; // // The Starting X position, where to start drawing text. // $xStartPos = 0; // // The Starting Y position, where to start drawing text. // $yStartPos = 0; // // The default text message if no text message is given. // $genericTxt = ""; // // The button image, if not already given. // $genImage = "genericButton.gif"; ?> The Program: button.php The Code: <?php header("Content-type: image/gif"); include_once("vars.php"); if (!isset($color)) { $color = $txtCol; } if (!isset($fontsize)) { $fontsize = $defaultFont; } if (!isset($startX)) { $startX = $xStartPos; } if (!isset($startY)) { $startY = $yStartPos; } if (!isset($txt)) { $txt = $genericTxt; } if (!isset($tmpl_image)) { $tmpl_image = $genImage; } $im = ImageCreateFromGif($tmpl_image); switch ($color) { case 'w': $col = ImageColorAllocate($im, 255, 255, 255); break; case 'b': $col = ImageColorAllocate($im, 0, 0, 0); break; case 'r': $col = ImageColorAllocate($im, 255, 0, 0); break; case 'g': $col = ImageColorAllocate($im, 0, 255, 0); break; case 'bl': $col = ImageColorAllocate($im, 0, 0, 255); break; } ImageString($im, $fontsize, $startX, $startY, $txt, $col); ImageGif($im); ImageDestroy($im); ?> CommentsIf you are anything like me, doing the same things over and over annoys you. One area where things can become redundant is when creating navigation buttons for your Web site. Every button is the same size and has the same background; the only thing different is the text contained within the button. In the preceding recipe, we remedy this by creating a script in which you fill in a few variable parameters and the script creates all your buttons for you. Of course, this script might need a little modification for your purposes (such as adding more colors for the text to be drawn), but the basic concept remains the same. |