tutorial 3.1:

Working with text in Processing

Processing provides many tools for working with text, including a high level of control over typography and the ability to animate text and add interactivity to text elements. This tutorial is a very basic introduction to all that you can do with text in Processing; for more information I recommend taking a look at the Processing Reference page and at contributed libraries for Typography.



1) The most basic use of text in Processing involves the text() function.

This allows you to specify the text to be displayed, the position of the text, and (optionally) the size of the text box.

String s = "The quick brown fox jumped over the lazy dog.";
fill(50);
text(s, 10, 10, 70, 80);  // Text wraps within text box


2) Text boxes can be used to display dynamic as well as static variables.

It can sometimes be useful to display on the screen information about the sketch for purposes of debugging, such as framerate and mouse position:

void displayInfo(int myX, int myY) {
  fill(100);
  String string_one = "framerate: "+frameRate;
  String string_two = "mouseX: "+mouseX;
  String string_three = "mouseY: "+mouseY;
  text(string_one, myX, myY);
  text(string_two, myX, myY+10);
  text(string_three, myX, myY+20);
}

This function displays three system variables that are automatically updated while the sketch is running; you could similarly display variables that you've defined in this fashion.

3) Text boxes can be displayed selectively, such as on rollover.

Text boxes can be displayed when you click or rollover a particular object, and generic functions such as the one below can be used to produce a rollover for a large number of objects:

void testRollover(int myX, int myY, float myValue, int myRadius) {
  if ((mouseX>(myX-myRadius)) && (mouseX<(myX+myRadius)) && (mouseY>(myY-myRadius)) && (mouseY<(myY+myRadius))) {
    println("it's a hit!! The value is "+myValue);
    noStroke();
    fill(0, 85);
    rect(myX+5, myY-15, 40, 13);
    fill(255);
    text(myValue, myX+10, myY-5);
  }
}

In this function the parameters are x-position and y-position of the object, the value to be displayed, and a radius within which a rollover is recognized.



Mini-exercise:



How could you adapt the 'testRollover' function to automatically adjust the size of the rectangle to the amount of text displayed?



You can download the code used in this example here.