You are here

function textimage_wrap_text in Textimage 6.2

Same name and namespace in other branches
  1. 5.2 textimage.module \textimage_wrap_text()
  2. 5 textimage.module \textimage_wrap_text()
  3. 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 606

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 (drupal_preg_match('/[' . TEXTIMAGE_PREG_CLASS_PUNCTUATION . '][' . TEXTIMAGE_PREG_CLASS_SEPARATOR . ']*|[' . TEXTIMAGE_PREG_CLASS_SEPARATOR . ']+/u', $text, $match, PREG_OFFSET_CAPTURE, $end)) {
      $end = $match[0][1] + drupal_strlen($match[0][0]);
    }
    else {
      $end = drupal_strlen($text);
    }

    // Fetch text, removing trailing white-space and measure it.
    $line = preg_replace('/[' . TEXTIMAGE_PREG_CLASS_SEPARATOR . ']+$/u', '', drupal_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 (drupal_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 = drupal_strlen($line) ? $begin + drupal_strlen($line) : $end;
      }

      // We have a valid fit for the next line. Insert a line-break and reset
      // the search interval.
      $text = drupal_substr($text, 0, $fit) . "\n" . drupal_substr($text, $fit);
      $end = $begin = ++$fit;
    }
    else {

      // We can fit this text. Wait for now.
      $fit = $end;
    }
    if ($end == drupal_strlen($text)) {

      // All text fits. No more changes are needed.
      break;
    }
  }
  return $text;
}