Search code examples
randomprocessingtext-size

how to set random text size on each letter once? (processing)


how can I set a random size for each letter that spreads out? I want each of them to have a different random size but I can't really figure out where to put textSize (random(10, 20)); because if I put it under draw it just loops over and over again that each frame the text size of each letter changes but when I put it under setup it just changes the size of all the letters.

String message = "Alice fell into the rabbit hole";
int x =  130;
int y = 90;

Letter[] letters;

void setup() {
  size(260, 200);
  letters = new Letter[message.length()];
  textSize (random(10, 20));

  for (int i = 0; i < message.length(); i++) { 
    letters[i] = new Letter(x, y, message.charAt(i));
    //x += textWidth(message.charAt(i));
  }
}

void draw() { 
  background(255);
  for (int i = 0; i < letters.length; i++) { 
    letters[i].display(); 
    letters[i].shake();
  }
}

class Letter {
  char letter;
  float x, y;

  Letter (float x, float y, char letter) {
    this.x = x;
    this.y = y;
    this.letter = letter;
  }

  void display() {
    fill(0);
    textAlign(CENTER, CENTER);
    text(letter, x, y);
  }

  void shake() {
    x += random(-2, 2);
    y += random(-2, 2);
  }
}

Solution

  • Your Letter class encapsulates everything about a specific letter. So if you want a random size for each letter, then you'd store that size in the Letter class.

    If you want the size to be the same for a single letter throughout the lifetime of the program, then you'd set that size in the constructor.

    Then you would use that size in the display() function before you draw the letter.