13.09.2016 Views

PHP and MySQL Web Development 4th Ed-tqw-_darksiderg

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

504 Chapter 22 Generating Images<br />

The $width variable is the total width of the canvas you will use.You also set up the<br />

left <strong>and</strong> right margins (with $left_margin <strong>and</strong> $right_margin, respectively); the “fatness”<br />

<strong>and</strong> spacing between the bars ($bar_height <strong>and</strong> $bar_spacing); <strong>and</strong> the font, font<br />

sizes, <strong>and</strong> label position ($font, $title_size, $main_size, $small_size, <strong>and</strong><br />

$text_indent).<br />

Given these base values, you can then make a few calculations.You want to draw a<br />

baseline that all the bars stretch out from.You can work out the position for this baseline<br />

by using the left margin plus an allowance for the text labels for the x coordinate <strong>and</strong><br />

again an estimate from the sketch for the y coordinate.You could get the exact width of<br />

the longest name instead if flexibility is important.<br />

You also work out two important values: first, the distance on the graph that represents<br />

one unit:<br />

$bar_unit = ($width-($x+$right_margin)) / 100;<br />

// one “point” on the graph<br />

This is the maximum length of the bars—from the baseline to the right margin—divided<br />

by 100 because the graph is going to show percentage values.<br />

The second value is the total height that you need for the canvas:<br />

$height = $num_c<strong>and</strong>idates * ($bar_height + $bar_spacing) + 50;<br />

This value is basically the height per bar times the number of bars, plus an extra amount<br />

for the title. Part 3 is shown in Listing 22.5.3.<br />

Listing 22.5.3<br />

Added<br />

show_poll.php —Part 3 Sets Up the Graph, Ready for the Data to Be<br />

/*******************************************<br />

Set up base image<br />

*******************************************/<br />

// create a blank canvas<br />

$im = imagecreatetruecolor($width,$height);<br />

// Allocate colors<br />

$white=imagecolorallocate($im,255,255,255);<br />

$blue=imagecolorallocate($im,0,64,128);<br />

$black=imagecolorallocate($im,0,0,0);<br />

$pink = imagecolorallocate($im,255,78,243);<br />

$text_color = $black;<br />

$percent_color = $black;<br />

$bg_color = $white;<br />

$line_color = $black;<br />

$bar_color = $blue;<br />

$number_color = $pink;<br />

// Create "canvas" to draw on<br />

imagefilledrectangle($im,0,0,$width,$height,$bg_color);

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!