06.01.2013 Views

Learning Processing: A Beginner's Guide to Programming Images ...

Learning Processing: A Beginner's Guide to Programming Images ...

Learning Processing: A Beginner's Guide to Programming Images ...

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

312 <strong>Learning</strong> <strong>Processing</strong><br />

textAlign(CENTER);<br />

text( " This text is centered. " ,width/2,60);<br />

textAlign (LEFT) ;<br />

text( " This text is left aligned. " ,width/2,100);<br />

textAlign(RIGHT);<br />

text( " This text is right aligned. " ,width/2,140);<br />

}<br />

textWidth( ) —Calculates and returns the width of any character or text string.<br />

Let’s say we want <strong>to</strong> create a news ticker, where text scrolls across the bot<strong>to</strong>m of the screen from left<br />

<strong>to</strong> right . When the news headline leaves the window, it reappears on the right-hand side and scrolls<br />

again. If we know the x location of the beginning of the text and we know the width of that text, we can<br />

determine when it is no longer in view (see Figure 17.4). textWidth( ) gives us that width.<br />

To start, we declare headline, font, and x location variables, initializing them in setup( ) .<br />

// A headline<br />

String headline = " New study shows computer programming lowers cholesterol. " ;<br />

PFont f; // Global font variable<br />

float x; // Horizontal location of headline<br />

void setup() {<br />

f = createFont( " Arial " ,16,true); // Loading font<br />

x = width; // Initializing headline off-screen <strong>to</strong> the right<br />

}<br />

Th e draw( ) function is similar <strong>to</strong> our bouncing ball example in Chapter 5. First, we display the text at the<br />

appropriate location.<br />

// Display headline at x location<br />

textFont(f,16);<br />

textAlign(LEFT);<br />

text(headline,x,180);<br />

We change x by a speed value (in this case a negative number so that the text moves <strong>to</strong> the left.)<br />

// Decrement x<br />

x = x – 3;<br />

textAlign() sets the alignment<br />

for displaying text. It takes one<br />

argument: CENTER, LEFT, or RIGHT.<br />

Now comes the more diffi cult part. It was easy <strong>to</strong> test when a circle reached the left side of the screen. We<br />

would simply ask: is x less than 0? With the text, however, since it is left-aligned, when x equals zero, it<br />

is still viewable on screen. Instead, the text will be invisible when x is less than 0 minus the width of the<br />

text (see Figure 17.4 ). When that is the case, we reset x back <strong>to</strong> the right-hand side of the window, that<br />

is, width .

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!