Text Justification?

edited March 2018 in Questions about Code

Hi all!

I've googled this and I've come across a lot of people asking about it but not necessarily knowing if this is a feature. Getting a bit stuck here in terms of syntax.

I'm using the textWidth reference as a base.


void setup(){
size(500,500);
textSize(28);

char c = 'T';
float cw = textWidth(c);
text(c, 0, 40);
line(cw, 0, cw, 50); 

String s = "Tokyo is the greatest city in the entire world";
float sw = textWidth(s);
if (textWidth(s) > width){
  
  text(s, 0, 85);
  println("true");
}
line(sw, 50, sw, 100);
}

I think the key lies within if (textWidth(s) > width) but can someone give me a pointer in terms of how to write it so that it will break when the sentence hits the width of the screen, preferably on a space so it makes sense? Is it simply "\n"? If so, how would the syntax work out?

Thank you!

Answers

  • You may use text() with five parameters: top left corner and bottom right corner pluss the string of text. The text inside will then automatically break up into lines in order to fit inside that box.

  • Yeah, look at reference for text()

    It’s very simple

  • Are you asking about line breaks?

    Or are you asking how to create fully justified text (flush left and flush right)?

  • edited April 2018

    Line wrapping (textAlign, LEFT / CENTER / RIGHT) is automatic.

    If you have set line breaks and want to full justify each line, you can use a feedback loop to change the text size for each line by measuring its textWidth and then changing the text size and measuring again until you hit the magic number.

    Screen Shot 2018-03-22 at 9.32.15 AM

    However, Processing does not (I believe) support letter kerning or word-spaced justification. That means you cannot full justify a paragraph of e.g 12pt font.

    Screen Shot 2018-03-22 at 9.32.44 AM

    At least, you can't do this without breaking out individual letters or words in your loop and placing each one with a separate text call. For an old discussion of this, see:

  • @Eeyorelife @Chrisir thank you, classic case of overthinking and not looking!

    and @jeremydouglass, yes I was also looking for that but didn't articulate it -- I saw some of the relics of people asking for this in the past and wondered if there were any updates. Shame, I like the look of kerning (will keep that word in mind next time). I'll play around with it some more.

    Thank you!

  • Also, just to clarify, the second picture I provided doesn't actually use kerning (space between individual letters) -- it expands the space between words but leaves letter spacing alone. So for the you would need to chunk by words and measure their while packing each line, then space them across the line.

    For previous related discussions of bolded words or colored words (which also require chunking text by word before layout) search the forum for 'bricklaying':

Sign In or Register to comment.