function textimage_wrap_text in Textimage 5
Same name and namespace in other branches
- 5.2 textimage.module \textimage_wrap_text()
- 6.2 textimage.module \textimage_wrap_text()
- 7.2 textimage.utils.inc \textimage_wrap_text()
Wrap text for rendering at a given width.
1 call to textimage_wrap_text()
- textimage_text_to_image in ./
textimage.module - Generate an image containing text with the given parameters.
File
- ./
textimage.module, line 944
Code
function textimage_wrap_text($text, $fontsize, $font, $maximum_width) {
// State variables for the search interval
$end = 0;
$begin = 0;
$fit = $begin;
// Note: we count in bytes for speed reasons, but maintain character boundaries.
while (true) {
// Find the next wrap point (always after trailing whitespace).
if (preg_match('/[' . PREG_CLASS_PUNCTUATION . '][' . PREG_CLASS_SEPARATOR . ']*|[' . PREG_CLASS_SEPARATOR . ']+/u', $text, $match, PREG_OFFSET_CAPTURE, $end)) {
$end = $match[0][1] + strlen($match[0][0]);
}
else {
$end = strlen($text);
}
// Fetch text, removing trailing white-space and measure it.
$line = preg_replace('/[' . PREG_CLASS_SEPARATOR . ']+$/u', '', substr($text, $begin, $end - $begin));
$width = textimage_measure_text_width($line, $fontsize, $font);
// See if $line extends past the available space.
if ($width > $maximum_width) {
// If this is the first word, we need to truncate it.
if ($fit == $begin) {
// Cut off letters until it fits.
while (strlen($line) > 0 && $width > $maximum_width) {
$line = drupal_substr($line, 0, -1);
$width = textimage_measure_text_width($line, $fontsize, $font);
}
// If no fit was found, the image is too narrow..
$fit = strlen($line) ? $begin + strlen($line) : $end;
}
// We have a valid fit for the next line. Insert a line-break and reset
// the search interval.
$text = substr($text, 0, $fit) . "\n" . substr($text, $fit);
$end = $begin = ++$fit;
}
else {
// We can fit this text. Wait for now.
$fit = $end;
}
if ($end == strlen($text)) {
// All text fits. No more changes are needed.
break;
}
}
return $text;
}