Text Wrapping

Friend asked me about this so thought I would post here, helpful code for wrapping text.

setup:

  
verdana.loadFont("verdana.ttf",8, true, true);  
verdana.setLineHeight(20.0f);  
  
string sometext = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.";   
  
text = wrapedString(sometext, 300);  
  

Wrap the string funciton

  
  
string wrapString(string text, int width) {  
	  
	string typeWrapped = "";  
	string tempString = "";  
	vector <string> words = ofSplitString(text, " ");  
	  
	for(int i=0; i<words.size(); i++) {  
  
		string wrd = words[i];  
		cout << wrd << endl;  
		  
		tempString += wrd + " ";  
		int stringwidth = verdana.stringWidth(tempString);  
		if(stringwidth >= width) {  
			tempString = "";  
			typeWrapped += "\n";  
		}  
		  
		typeWrapped += wrd + " ";  
	}  
	  
	return typeWrapped;  
	  
}  
  

Draw

  
ofSetColor(0x000000);  
verdana.drawString(text, 100, 210);  
  

This is super helpful, I’ve done this before in the past but in a WAY more brutal way…this both makes me happy and want to kill myself for the way I did it in the past, didn’t realize you could just put a \n in there for ofTrueTypeFont, thanks a lot!

This worked pretty well for me for a while. However, after trying it with a number of different strings, it appears there are a few issues with the wrapString method:

– After a newline, tempString doesn’t include the freshly-wrapped word.
– tempString includes an extra space at the end, so the line is measured as longer than it needs to be.
– The returned typeWrapped string includes an extra space at the end.

I will therefore bid the following for wrapString():

  
  
string wrapString(string text, int width) {  
	  
	string typeWrapped = "";  
	string tempString = "";  
	vector <string> words = ofSplitString(text, " ");  
	  
	for(int i=0; i<words.size(); i++) {  
		  
		string wrd = words[i];  
		  
		// if we aren't on the first word, add a space  
		if (i > 0) {  
			tempString += " ";  
		}  
		tempString += wrd;  
		  
		int stringwidth = verdana->stringWidth(tempString);  
  
		if(stringwidth >= width) {  
			typeWrapped += "\n";  
			tempString = wrd;		// make sure we're including the extra word on the next line  
		} else if (i > 0) {  
			// if we aren't on the first word, add a space  
			typeWrapped += " ";  
		}  
		  
		typeWrapped += wrd;  
	}  
	  
	return typeWrapped;  
	  
}  
  

This has worked for me so far; thanks for posting the original!

1 Like

where do i wrap the string funciton?
anything i have to do in the header?

thanks!