We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
Page Index Toggle Pages: 1
text formatting (Read 423 times)
text formatting
Apr 23rd, 2009, 9:29am
 
Hi, I am new to Processing and I was wondering if anyone could help me with this:
I have this text file uploaded into a string array and it runs over 4 lines (elements 0,1,2,3)
I have to center the first two lines
And format the [3] 4th line so that it runs over many lines and is left aligned.
here is a some copies of my setup and draw:

void setup()
{
 size(600, 600);

//this is the information used for the text and font
 font = loadFont("Tahoma-48.vlw");

 textFont(font, 16);
 textAlign(LEFT);
 smooth();
 
 prose = loadStrings("prose.txt");

 lineHeight = textDescent() + textAscent();
 x = 10;
 y = lineHeight;

}

void draw()
{
 background(32);
 
 fill(255);

 y = lineHeight;

 for(int i = 0; i < prose.length; i++)
 {
   text(prose[i], x, y);
       
   float lineWidth = textWidth(prose[i]);
 
   y += lineHeight;
//formatting the first two lines
   prose[0] = prose[0].toUpperCase();
   stroke(255);
   line(x,lineHeight,textWidth(prose[0]),lineHeight);
   prose[1] = prose[1].toLowerCase();
   
 }

Huh
Re: text formatting
Reply #1 - May 19th, 2009, 2:48pm
 
Doing proper line/word breaks can be kind of tricky and depends on what kinds of breaks are acceptable. A basic (but possibly ugly) way to do it is shown below, basically add a character to a string and see if it will still fit on screen. However you will want to add a few more conditions to do things like hyphenate or backup and jump to a new line if the next word does not fit on the current line.

Code:

void draw(){
 String text_line = "";
 for(float w=0; w < width;){
 text_line += "A";  // instead of appending A append the next char from your string
 w = textWidth(text_line);
 fill(0);  
 }
 //this draws a single line that goes from one end of the screen to the other
 //you could repeat this process (translating down after each line)
 text(text_line, 0, height/2);
}
Re: text formatting
Reply #2 - May 19th, 2009, 2:50pm
 
Actually now that i think of it, in the example posted above, instead of appending 1 character at a time, append the next word from the text and check if it fits and that way you can easily break to a new line that the next word will fit on. You will have to take care of the case where a single word cannot fit on a line (if your space is small or the words rather long), in which chase you would do the character breaking as in the code above. Hope this helps
Page Index Toggle Pages: 1