GD::Text::Align allows us to do this easily. In the above example,
the TITLE_Y_COORD constant is really the top
margin, and TITLE_X_COORD is the left margin
(remember coordinates start at the top left corner of the image in
GD). There is nothing wrong with a constant for the top margin, but
if we want to have a centered title, then we should calculate
TITLE_X_COORD dynamically.
Thus, let's look at how we could modify
loads.cgi to do this with GD::Text::Align.
First, let's include the GD::Text::Align module at the start of
the script:
use GD::Text::Align;
Next, we can replace the line that places the title string (in the
area_graph subroutine) with the following:
# Add Centered Title
my $title = GD::Text::Align->new(
$image,
font => gdLargeFont,
text => TITLE_TEXT,
color => $text_color,
valign => "top",
halign => "center",
);
$title->draw( IMAGE_SIZE / 2, TITLE_Y_COORD );
We create a GD::Text::Align object by passing our GD object,
$image, and a number of parameters describing our
text, and the draw method adds our title to the
image. We should then remove the TITLE_X_COORD
constant, which we know longer use; you may also want to rename
TITLE_Y_COORD to something more meaningful in this
context, such as TITLE_TOP_MARGIN.
Besides allowing you to place aligned text, GD::Text::Align also lets
you obtain coordinates for the bounding box for a text string before
you place it so you can make adjustments if necessary (such as
reducing the size of the font). It also supports True Type fonts and
placing text at angles. Refer to the GD::Text::Align online
documentation for more information.