You are here

function _textimage_wrap_text in Textimage 7.3

Wrap text for rendering at a given width.

Parameters

object $image: Image object.

string $text: Text string in UTF-8 encoding.

int $font_size: Font size.

string $font_uri: URI of the TrueType font to use.

int $maximum_width: Maximum width allowed for each line.

Return value

string Text string, with newline characters to separate each line.

1 call to _textimage_wrap_text()
_textimage_get_text_wrapper in effects/textimage_text.inc
Get the image containing the text.

File

effects/textimage_text.inc, line 1245
Implementation of the 'textimage_text' image effect.

Code

function _textimage_wrap_text($image, $text, $font_size, $font_uri, $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) {
    $match = array();

    // Find the next wrap point (always after trailing whitespace).
    if (drupal_preg_match('/[' . PREG_CLASS_PUNCTUATION . '][' . PREG_CLASS_SEPARATOR . ']*|[' . 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('/[' . PREG_CLASS_SEPARATOR . ']+$/u', '', drupal_substr($text, $begin, $end - $begin));
    $width = _textimage_measure_text_width($image, $line, 1, $font_size, $font_uri);

    // 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($image, $line, 1, $font_size, $font_uri);
        }

        // 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.
      if (drupal_substr($text, $fit - 1, 1) == ' ') {
        $first_part = drupal_substr($text, 0, $fit - 1);
      }
      else {
        $first_part = drupal_substr($text, 0, $fit);
      }
      $last_part = drupal_substr($text, $fit);
      $text = $first_part . "\n" . $last_part;
      $begin = ++$fit;
      $end = $begin;
    }
    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;
}