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.

498 Chapter 22 Generating Images<br />

The left side of the baseline is specified as the origin of measurements—that is, x<br />

coordinate 0 <strong>and</strong> y coordinate 0. Coordinates above the baseline have a positive x coordinate,<br />

<strong>and</strong> coordinates below the baseline have a negative x coordinate.<br />

In addition, text might actually have coordinate values that sit outside the bounding<br />

box. For example, the text might actually start at an x coordinate of –1.<br />

What this all adds up to is the fact that care is required when you’re performing calculations<br />

with these numbers.<br />

You work out the width <strong>and</strong> height of the text as follows:<br />

$right_text = $bbox[2]; // right co-ordinate<br />

$left_text = $bbox[0]; // left co-ordinate<br />

$width_text = $right_text - $left_text; // how wide is it?<br />

$height_text = abs($bbox[7] - $bbox[1]); // how tall is it?<br />

After you have this information, you test the loop condition:<br />

} while ( $font_size>8 &&<br />

( $height_text>$height_image_wo_margins ||<br />

$width_text>$width_image_wo_margins )<br />

);<br />

You test two sets of conditions here.The first is that the font is still readable; there’s<br />

no point in making it much smaller than 8-point type because the button becomes too<br />

difficult to read.The second set of conditions tests whether the text will fit inside the<br />

drawing space you have available for it.<br />

Next, you check to see whether the iterative calculations found an acceptable font<br />

size <strong>and</strong> report an error if not:<br />

if ( $height_text>$height_image_wo_margins ||<br />

$width_text>$width_image_wo_margins )<br />

{<br />

// no readable font size will fit on button<br />

echo ‘Text given will not fit on button.’;<br />

}<br />

Positioning the Text<br />

If all was okay, you next work out a base position for the start of the text.This is the<br />

midpoint of the available space.<br />

$text_x = $width_image/2.0 - $width_text/2.0;<br />

$text_y = $height_image/2.0 - $height_text/2.0 ;<br />

Because of the complications with the baseline relative coordinate system, you need to<br />

add some correction factors:<br />

if ($left_text < 0)<br />

$text_x += abs($left_text);<br />

// add factor for left overhang

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

Saved successfully!

Ooh no, something went wrong!