Loading...
Logo
Processing Forum
Hi all,

I'm trying to align a block of text to a right edge, and it looks like the automated line breaks are still put after spaces in the way they are done for textAlign(LEFT), but this ends up giving me an uneven amount of space at the end of each right-aligned line.

Has anyone else had this problem?  Am I doing something wrong?

Thanks in advance...
Copy code
  1. String forecast = "Mostly cloudy in the morning, then partly cloudy. High of 63F. Winds from the ENE at 5 to 15 mph.";

  2. size(500,500);
  3. background(0);
  4. fill(255);
  5. textFont(createFont("Kievit-Regular",30));
  6. text(forecast, 50, 20, 400, 200);
  7. // >>>>>>> DEBUG
  8. stroke(color(0, 255, 255));
  9. noFill();
  10. rect(50, 20, 400, 200);
  11. noStroke();
  12. // -------------
  13. fill(255);
  14. textAlign(RIGHT);
  15. text(forecast, 50, 270, 400, 200);
  16. // >>>>>>> DEBUG
  17. stroke(color(0, 255, 255));
  18. noFill();
  19. rect(50, 270, 400, 200);
  20. noStroke();

Replies(2)

The problem is each line (except the last) includes a space. Although it may be invisible it affects the aligning.

So the solution is to move the whole text block by the width of one space (or similarly increase the textblock width by one space). Of course this moves the last line (which doesn't end with a space) a bit to far, so to equalize all lines, add a space at the end of the String. See the below example.

Adapted Code
Copy code
  1. String forecast = "Mostly cloudy in the morning, then partly cloudy. High of 63F. Winds from the ENE at 5 to 15 mph.";

  2. size(500,750);
  3. background(0);
  4. fill(255);
  5. textFont(createFont("Kievit-Regular",30));
  6. text(forecast, 50, 20, 400, 200);
  7. // >>>>>>> DEBUG
  8. stroke(color(0, 255, 255));
  9. noFill();
  10. rect(50, 20, 400, 200);
  11. noStroke();
  12. // -------------
  13. fill(255);
  14. textAlign(RIGHT);
  15. text(forecast, 50, 270, 400, 200);
  16. // >>>>>>> DEBUG
  17. stroke(color(0, 255, 255));
  18. noFill();
  19. rect(50, 270, 400, 200);
  20. noStroke();
  21. // -------------
  22. fill(255);
  23. textAlign(RIGHT);
  24. forecast += " "; // add a space at the end of the String
  25. float spaceWidth = textWidth(" "); // get the width of one space
  26. // correct all lines for the end space by adding spaceWidth to x (aka moving the whole text block)
  27. text(forecast, 50+spaceWidth, 520, 400, 200);
  28. // >>>>>>> DEBUG
  29. stroke(color(0, 255, 255));
  30. noFill();
  31. rect(50, 520, 400, 200);
  32. noStroke();