Word Wrap in Processing

I’ve been meaning to add something to processing hacks for quite some time now. This morning, I needed a basic function to wrap text in Processing so came up with this snippet.

// Function to return an ArrayList of Strings
// (maybe redo to just make simple array?)
// Arguments: String to be wrapped, maximum width in pixels of line
ArrayList wordWrap(String s, int maxWidth) {
  // Make an empty ArrayList
  ArrayList a = new ArrayList();
  float w = 0;    // Accumulate width of chars
  int i = 0;      // Count through chars
  int rememberSpace = 0; // Remember where the last space was
  // As long as we are not at the end of the String
  while (i < s.length()) {
    // Current char
    char c = s.charAt(i);
    w += textWidth(c); // accumulate width
    if (c == ' ') rememberSpace = i; // Are we a blank space?
    if (w > maxWidth) {  // Have we reached the end of a line?
      String sub = s.substring(0,rememberSpace); // Make a substring
      // Chop off space at beginning
      if (sub.length() > 0 && sub.charAt(0) == ' ') {
        sub = sub.substring(1,sub.length());
      }
      // Add substring to the list
      a.add(sub);
      // Reset everything
      s = s.substring(rememberSpace,s.length());
      i = 0;
      w = 0;
    }
    else {
      i++;  // Keep going!
    }
  }

  // Take care of the last remaining line
  if (s.length() > 0 && s.charAt(0) == ' ') {
    s = s.substring(1,s.length());
  }
  a.add(s);

  return a;
}

3 Responses to “Word Wrap in Processing”  

  1. 1 JohnG

    I think it might be more efficient to start at maxWidth, and work backwards looking for a space, rather than from the start working forwards finding the last space before the end.

  2. 2 seltar

    Got my own version which returns a string with linebreaks:

      public String WordWrap(String strText, int iWidth){
    
        if( strText.length() = iLineNO){
          for(int iEn = iLineNO; iEn > 1; iEn--){         // work backwards from the max len to 1 looking for a space
            sChar = sResult.charAt(iEn);
            if(sChar == \' \'){             // found a space
              sResult = remove(sResult, iEn , 1);     // Remove the space
              sResult = insert(sResult, iEn, \"\\n\");     // insert a line feed here,
              iLineNO  = iWidth;             // increment
              lines  ;
              break;
            }
          }
        }
        return sResult;
      }
    
      public String remove(String str, int pos, int len){
        String ret = \"\";
        for(int i = 0; i =pos && i
    
  3. 3 Daniel

    Ah, cool, thanks for the suggestions all! This was my quick and dirty solution . . .

Leave a Reply