Skip to content

Instantly share code, notes, and snippets.

@ifnull
Last active December 20, 2015 15:19
Show Gist options
  • Save ifnull/6153515 to your computer and use it in GitHub Desktop.
Save ifnull/6153515 to your computer and use it in GitHub Desktop.
Multi-line imagefttext method
<?php
public function multilineImageFTText($canvas, $fontSize, $font, $color, $copy, $start_x, $start_y, $width, $alignment)
{
// Holds lines
$strings = array();
// Placeholder for first element
$strings[] = '';
// Split copy into array using space
$words = explode(' ', $copy);
// Get font height
$tb = imageTTFBbox($fontSize, 0, $font, 'foobar');
$fontHeight = abs($tb[1] + $tb[5]);
$start_y = $start_y + $fontHeight;
// Loop over words
foreach ($words as $key => $word) {
// Set array pointer to the end of the array and add a space to the end.
$str = end($strings).' ';
// Create a temp string to test
$tmpString = trim($str.$word);
// Calulate width of temp string
$tb = imageTTFBbox($fontSize, 0, $font, $tmpString);
$tmpWidth = abs($tb[0] + $tb[2]);
// Check if the temp string width exceed allocated width
if($tmpWidth <= $width){
// Append to string in last array element
$strings[key($strings)] = $tmpString;
} else {
// Create a new string element and add current word
$strings[] = $word;
}
}
// Loop over strings
foreach ($strings as $key => $string) {
// Get string width
$tb = imageTTFBbox($fontSize, 0, $font, $string);
$tmpWidth = abs($tb[0] + $tb[2]);
switch ($alignment) {
case 'center':
$offsetLeft = ($width - $tmpWidth) / 2;
break;
case 'right':
$offsetLeft = ($width - $tmpWidth);
break;
default:
$offsetLeft = 0;
break;
}
// Add string to canvas
imagefttext($canvas, $fontSize, 0, $start_x + $offsetLeft, $start_y, $color, $font, $string);
// Increment line height
$start_y = $start_y + $fontHeight;
}
return $canvas;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment