note 81830 deleted from function.imagettftext by nlopess
| From: | nlopess@php.net | Date: | Tue, 18 Mar 2008 19:38:17 +0000 |
| Subject: | note 81830 deleted from function.imagettftext by nlopess | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-137178@lists.php.net to get a copy of this message | ||
Note Submitter: sk89q
----
Function I wrote a few years ago to draw text and align it (not justified).
<?php
function imagettftextwrapped(&$image, $top, $left, $max_width, $align, $font, $color, $text,
$size)
{
$text_lines = explode("\n", $text);
$lines = array();
$line_widths = array();
$largest_line_height = 0;
foreach($text_lines as $block)
{
$current_line = ''; // Reset current line
$words = explode(' ', $block); // Split the text into an array of single words
$first_word = true;
$last_width = 0;
for($i = 0; $i < count($words); $i++)
{
$item = $words[$i];
$dimensions = imagettfbbox($size, 0, $font, $current_line . ($first_word ? ''
: ' ') . $item);
$line_width = $dimensions[2] - $dimensions[0];
$line_height = $dimensions[1] - $dimensions[7];
if($line_height > $largest_line_height) $largest_line_height = $line_height;
if($line_width > $max_width && !$first_word)
{
$lines[] = $current_line;
$line_widths[] = $last_width ? $last_width : $line_width;
if($i == count($words) - 1)
{
continue;
}
$current_line = $item;
}
else
{
$current_line .= ($first_word ? '' : ' ') . $item;
}
if($i == count($words) - 1)
{
$lines[] = $current_line;
$line_widths[] = $line_width;
}
$last_width = $line_width;
$first_word = FALSE;
}
}
$i = 0;
foreach($lines as $line)
{
if($align == ALIGN_CENTER)
{
$left_offset = ($max_width - $line_widths[$i]) / 2;
}
elseif($align == ALIGN_RIGHT)
{
$left_offset = ($max_width - $line_widths[$i]);
}
imagettftext($image, $size, 0, $left + $left_offset, $top + $largest_line_height +
($largest_line_height * $i), $color, $font, $line);
$i++;
}
return $height;
}
?>