note 109589 modified in function.imagettfbbox by danbrown
| From: | danbrown@php.net | Date: | Fri, 10 Aug 2012 16:25:10 +0000 |
| Subject: | note 109589 modified in function.imagettfbbox by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-190029@lists.php.net to get a copy of this message | ||
Automatic line breaks: This simple function is able automatically create line breaks if you want to
write a text on an image. All you have to specify is a maximum
length. <?php function
write_multiline_text($image, $font_size, $color, $font, $text, $start_x, $start_y, $max_width)
{ 		//split the
string 		//build new string word for
word 		//check everytime you add a word if string still
fits 		//otherwise, remove last word, post current string and start
fresh on a new line 		$words = explode(" ",
$text); 		$string =
""; 		$tmp_string =
""; 		 		for($i = 0;
$i < count($words);
$i++) 		{ 			$tmp_string .=
$words[$i]."
"; 			 			//check
size of string 			$dim = imagettfbbox($font_size, 0, $font,
$tmp_string); 			 			if($dim[4]
<
$max_width) 			{ 				$string
= $tmp_string; 			} else
{ 				$i--; 				$tmp_string
= ""; 				imagettftext($image, 11, 0,
$start_x, $start_y, $color, $font,
$string); 				 				$string
= ""; 				$start_y += 22; //change this
to adjust line-height. Additionally you could use the information from the "dim"
array to automatically figure out how much you have to "move
down" 			} 		} 								 		imagettftext($image,
11, 0, $start_x, $start_y, $color, $font, $string); //"draws" the rest of the
string ?>
--was--
Automatic line breaks: This simple function is able automatically create line breaks if you want to
write a text on an image. All you have to specify is a maximum length.
function write_multiline_text($image, $font_size, $color, $font, $text, $start_x, $start_y,
$max_width)
{
//split the string
//build new string word for word
//check everytime you add a word if string still fits
//otherwise, remove last word, post current string and start fresh on a new line
$words = explode(" ", $text);
$string = "";
$tmp_string = "";
for($i = 0; $i < count($words); $i++)
{
$tmp_string .= $words[$i]." ";
//check size of string
$dim = imagettfbbox($font_size, 0, $font, $tmp_string);
if($dim[4] < $max_width)
{
$string = $tmp_string;
} else {
$i--;
$tmp_string = "";
imagettftext($image, 11, 0, $start_x, $start_y, $color, $font, $string);
$string = "";
$start_y += 22; //change this to adjust line-height. Additionally you could use the information
from the "dim" array to automatically figure out how much you have to "move
down"
}
}
imagettftext($image, 11, 0, $start_x, $start_y, $color, $font, $string); //"draws" the
rest of the string
http://php.net/manual/en/function.imagettfbbox.php