Search code examples
audiotextcolorsprocessingmetronome

How to differentiate text colour on individual letters in a string?


I'm new in this programming realm and working on a of visual metronome. Each letters has got a drum pattern assigned to it.

I will be working on adding a click sound to it later on but want to figure out the visuals first. Unless some of you could help me with adding a sound every time the letter changes, that would be great!

Regarding the visual part though, I want to differentiate text colour on individual letters so the one on the left would be more prominent and the one on the right fainter.

Would some of you be able to help me with that?

Best, SHB

String[] words = {"A    ", "B    ", "C    ", "D    ", "E    ", "F    "}; 
int newIndex = 0;
int oldIndex = -1;
PFont SansSerif;

void setup() {
  size(700, 500);
  background(0);
  SansSerif = createFont("SansSerif", 162);
  textFont(SansSerif);
}

void draw() {
  frameRate(.6); 
  background(0);
  // Get a random element from array
  newIndex = int(random(words.length));
  
  if (oldIndex > -1) {
    fill(150);
    text(words[oldIndex]  + words[newIndex], 150, 300);
    println("old =", words[oldIndex] + " : " +  "new =", words[newIndex] ); 
  } else {
    fill(150);
    text(words[newIndex],  150, 300);
    println("new =", words[newIndex]);
  }
  oldIndex = newIndex;
}

Solution

  • By changing your chosen letters to a string and then looping through the characters you can change each one to a different color using charAt().

    String[] words = {"A    ", "B    ", "C    ", "D    ", "E    ", "F    "}; 
    int newIndex = 0;
    int oldIndex = -1;
    PFont SansSerif;
    String beat = "";
    int x = 0;
    
    void setup() {
      size(700, 500);
      background(255); // Changed to lighter background
      SansSerif = createFont("SansSerif", 162);
      textFont(SansSerif);
    }
    
    void draw() {
      frameRate(.6); 
      background(255); // Changed to lighter background
      // Get a random element from array
      newIndex = int(random(words.length));  
      if (oldIndex > -1) {
        beat = words[oldIndex] + words[newIndex];
        int x = 150;
        for (int i = 0; i < beat.length(); i++){
          if(i == 0){
            fill(0);
          } else {
            fill(150);
          }
          text(beat.charAt(i), x, 300);
          x += 60;
        }
        println("old =", words[oldIndex] + " : " +  "new =", words[newIndex] ); 
      } else {
        fill(0);
        text(words[newIndex],  150, 300);
        println("new =", words[newIndex]);
      }
      oldIndex = newIndex;
    }