Problem with textWidth()
in
Programming Questions
•
10 months ago
Hi all,
I am trying to make a sketch that switches between two modes: Clearly displaying sentences and displaying sentences in a big mess. I have therefore tried to make a class that let's me manipulate the placement of words in their original sentence. I pasted the code, and you can look at it, but I think my most important question is this:
Can I rely on textWidth() to make accurate placements of text?
Can I rely on textWidth() to make accurate placements of text?
In the Story class, I try to use it in setting up a sentence "from scratch", but the words are being placed overlapping each other when they should be placed with neat spaces between them. I even tried a mono font.
(And yes, I know the code is messy and uncommented. I think the interesting area is the .display() function of the Story class.)
(And yes, I know the code is messy and uncommented. I think the interesting area is the .display() function of the Story class.)
- /***
- Used for putting text in a big pile
- ***/
- Story[] stories;
- String[] strings;
- void setup() {
- size(750, 750);
- background(255);
- stroke(0);
- fill(0);
- rectMode(CORNER);
- strings = loadStrings("kartoffeltxt01.txt");
- stories = new Story[strings.length];
- textFont(createFont("AndaleMono", 11));
- textAlign(CENTER, CENTER);
- for (int i = 0; i < strings.length; i++) {
- stories[i] =
- new Story(strings[i],
- new PVector(random(width-40),
- random(height)));
- }
- }
- void draw() {
- background(255);
- rectMode(CORNER);
- float a = map(mouseX, 0, width, 0, 15);
- for (int j = 0; j < stories.length; j++) {
- stories[j].display();
- //text(stories[j].fullText, stories[j].presentLoc.x, stories[j].presentLoc.y+30);
- stories[j].update();
- }
- }
- class Story {
- String fullText;
- String[] words;
- PVector orgLoc;
- PVector presentLoc;
- Story(String tempText, PVector tempLoc) {
- fullText = tempText;
- words = split(fullText, 'X');
- orgLoc = tempLoc;
- presentLoc = orgLoc;
- }
- void update() {
- float inc = map(mouseX, 0, width, 0, 1);
- PVector m = new PVector(width/2, height/2);
- PVector p = PVector.sub(m, orgLoc);
- p.mult(inc);
- presentLoc = PVector.add(m, p);
- }
- void display() {
- float space = textWidth(' ');
- rectMode(CORNER);
- for (int i = 0; i < words.length; i++) {
- if (i == 0) {
- text(words[i], presentLoc.x, presentLoc.y);
- } else {
- float combinedWidth = 0;
- for (int j = 0; j < i; j++) {
- combinedWidth += textWidth(words[j])+space;
- }
- text(words[i], presentLoc.x + combinedWidth, presentLoc.y);
- /*
- fill(0, 30);
- noStroke();
- rect(presentLoc.x, presentLoc.y + 20, combinedWidth, 10);
- fill(0);
- stroke(0);
- */
- }
- }
- }
- }
1