-
-
Notifications
You must be signed in to change notification settings - Fork 173
Expand file tree
/
Copy pathindex.html
More file actions
702 lines (557 loc) · 24.2 KB
/
Copy pathindex.html
File metadata and controls
702 lines (557 loc) · 24.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
<table width="650">
<tr>
<td>
<p class="license">
This tutorial is from the book <a href="http://www.processing.org/learning/books/#shiffman">Learning Processing</a> by Daniel Shiffman, published by Morgan Kaufmann, © 2008 Elsevier Inc. All rights reserved. If you see any errors or have comments, please <a href="https://github.com/processing/processing-docs/issues?state=open">let us know</a>.
</p>
<h1 style="line-height: 0.7em;">Strings and Drawing Text</h1>
<h3 style="line-height: 0.7em;"><em>Daniel Shiffman</em></h3>
<p class="txt">
If you are looking to display text onscreen with Processing, you've got to first become familiar with the <a href="http://processing.org/reference/String.html">String</a> class. Strings are probably not a totally new concept for you, it's quite likely you've dealt with them before. For example, if you've printed some text to the message window or loaded an image from a file, you've written code like so:
</p>
<pre>
println("printing some text to the message window!"); // Printing a String
PImage img = loadImage("filename.jpg"); // Using a String for a file name
</pre>
<p class="txt">
Nevertheless, although you may have used a <a href="http://processing.org/reference/String.html">String</a> here and there, it's time to unleash their full potential.
</p>
<h3>Where do we find documentation for the String class?</h3>
<p class="txt">
Although technically a Java class, because Strings are so commonly used, Processing includes documentation in its reference: <a href="http://www.processing.org/reference/String.html">http://www.processing.org/reference/String.html</a>.
</p>
<p class="txt">
This page only covers some of the available methods of the String class. The full documentation can be found on java's <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html">String</a> page.
</p>
<h3>What is a String?</h3>
<p class="txt">
A String, at its core, is really just a fancy way of storing an array of characters. If we didn't have the String class, we'd probably have to write some code like this:
</p>
<pre>
char[] sometext = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'};
</pre>
<p class="txt">
Clearly, this would be a royal pain in the Processing behind. It's much simpler to do the following and make a String object:
</p>
<pre>
String sometext = "How do I make String? Type some characters between quotation marks!";
</pre>
<p class="txt">
It appears from the above that a String is nothing more than a list of characters in between quotes. Nevertheless, this is only the data of a String. We must remember that a String is an object with methods (which you can find on the reference page.) This is just like how we learned in the <a href="http://processing.org/learning/pixels/">Pixels tutorial</a> that a <a href="http://processing.org/reference/PImage.html">PImage</a> stores both the data associated with an image as well as the functionality: <a href="http://processing.org/reference/copy_.html">copy()</a>, <a href="http://processing.org/reference/loadPixels_.html">loadPixels()</a>, etc.
</p>
<p class="txt">
For example, the method <a href="http://processing.org/reference/String_charAt_.html">charAt()</a> returns the individual character in the String at a given index. Note that Strings are just like arrays in that the first character is index #0!
</p>
<pre>
String message = "some text here.";
char c = message.charAt(3);
println(c); // Results in 'e'
</pre>
<p class="txt">
Another useful method is <a href="http://processing.org/reference/String_length_.html">length()</a>. This is easy to confuse with the length property of an array. However, when we ask for the length of a String object, we must use the parentheses since we are calling a function called length() rather than accessing a property called length.
</p>
<pre>
String message = "This String is 34 characters long.";
println(message.length());
</pre>
<p class="txt">
We can also change a String to all uppercase using the <a href="http://processing.org/reference/String_toUpperCase_.html">toUpperCase()</a> method (<a href="http://processing.org/reference/String_toLowerCase_.html">toLowerCase()</a> is also available).
</p>
<pre>
String uppercase = message.toUpperCase();
println(uppercase);
</pre>
<p class="txt">
You might notice something a bit odd here. Why didn't we simply say "message.toUpperCase()" and then print "message" variable? Instead, we assigned the result of "message.toUpperCase()" to a new variable with a different name—"uppercase".
</p>
<p class="txt">
This is because a String is a special kind of object. It is immutable. An immutable object is one whose data can never be changed. Once we create a String, it stays the same for life. Anytime we want to change the String, we have to create a new one. So in the case of converting to uppercase, the method toUpperCase() returns a copy of the String object with all caps.
</p>
<p class="txt">
Finally, let's look at <a href="http://processing.org/reference/String_equals_.html">equals()</a>. Now, Strings can be compared with the "==" operator as follows:
</p>
<pre>
String one = "hello";
String two = "hello";
println(one == two);
</pre>
<p class="txt">
However, technically speaking, when "==" is used with objects, it compares the memory addresses for each object. Even though they contain the same data—"hello"-- if they are different object instances "==" could result in a false comparison. The <a href="http://processing.org/reference/String_equals_.html">equals()</a> function ensures that we are checking to see if two String objects contain the exact same sequence of characters, regardless of where that data is stored in the computer's memory.
</p>
<pre>
String one = "hello";
String two = "hello";
println(one.equals(two));
</pre>
<p class="txt">
Although both of the above methods return the correct result, it's safer to use equals(). Depending on how String objects are created in a sketch, "==" will not always work.
</p>
<p class="txt">
One other feature of String objects is concatenation, joining two Strings together. Strings are joined with the "+" operator. Plus, of course, usually means add in the case of numbers. When used with Strings, it means join.
</p>
<pre>
String helloworld = "Hello" + "World";
</pre>
<p class="txt">
Variables can also be brought into a String using concatenation.
</p>
<pre>
int x = 10;
String message = "The value of x is: " + x;
</pre>
<h3>Displaying Text</h3>
<p class="txt">
The easiest way to display a String is to print it in the message window. This is likely something you've done while debugging. For example, if you needed to know the horizontal mouse location, you would write:
</p>
<pre>
println(mouseX);
</pre>
<p class="txt">
Or if you needed to determine that a certain part of the code was executed, you might print out a descriptive message.
</p>
<pre>
println("We got here and we're printing out the mouse location!!!");
</pre>
<p class="txt">
While this is valuable for debugging, it's not going to help our goal of displaying text for a user. To place text on screen, we have to follow a series of simple steps.
</p>
<p class="txt">
<strong>1. Declare an object of type PFont.</strong>
</p>
<pre>
PFont f;
</pre>
<p class="txt">
<strong>2. Create the font by referencing the font name and the function createFont().</strong><br />
This should be done only once, usually in <a href="http://processing.org/reference/setup_.html">setup()</a>. Just as with loading an image, the process of loading a font into memory is slow and would seriously affect the sketch's performance if placed inside <a href="http://processing.org/reference/draw_.html">draw()</a>. You can see a list of your available system fonts by via <a href="http://processing.org/reference/PFont_list_.html">PFont.list()</a>. Because of limitations in Java, not all fonts can be used and some might work with one operating system and not others. When sharing a sketch with other people or posting it on the web, you may need to include a .ttf or .otf version of your font in the data directory of the sketch because other people might not have the font installed on their computer. Only fonts that can legally be distributed should be included with a sketch. In addition to the name of the font, you can specify the size as well as whether the font should be antialiased or not.
</p>
<pre>
f = createFont("Arial",16,true); // Arial, 16 point, anti-aliasing on
</pre>
<p class="txt">
<strong>3. Specify the font using textFont()</strong>.<br />
textFont() takes one or two arguments, the font variable and the font size, which is optional. If you do not include the font size, the font will be displayed at the size originally loaded. When possible, the text() function will use a native font rather than the bitmapped version created behind the scenes with createFont() so you have the opportunity to scale the font dynamically. When using P2D, the actual native version of the font will be employed by the sketch, improving drawing quality and performance. With the P3D renderer, the bitmapped version will be used and therefore specifying a font size that is different from the font size loaded can result in pixelated text.
</p>
<pre>
textFont(f,36);
</pre>
<p class="txt">
<strong>4. Specify a color using fill()</strong>.
</p>
<pre>
fill(255);
</pre>
<p class="txt">
<strong>5. Call the text() function to display text.</strong><br />
This function is just like shape or image drawing, it takes three arguments—the text to be displayed, and the x and y coordinate to display that text.
</p>
<pre>
text("Hello Strings!",10,100);
</pre>
<p class="txt">
Here are all the steps together:
</p>
<pre>
PFont f; // STEP 1 Declare PFont variable
void setup() {
size(200,200);
f = createFont("Arial",16,true); // STEP 2 Create Font
}
void draw() {
background(255);
textFont(f,16); // STEP 3 Specify font to be used
fill(0); // STEP 4 Specify font color
text("Hello Strings!",10,100); // STEP 5 Display Text
}
</pre>
<p class="txt">
Fonts can also be created using "Tools" → "Create Font." This will create and place a VLW font file in your data directory which you can load into a PFont object using <a href="http://processing.org/reference/loadFont_.html">loadFont()</a>.
</p>
<pre>
f = loadFont("ArialMT-16.vlw");
</pre>
<h3>Animating Text</h3>
<p class="txt">
Let's look at two more useful Processing functions related to displaying text:
</p>
<p class="txt">
<a href="http://processing.org/reference/textAlign_.html">textAlign()</a>—specifies RIGHT, LEFT or CENTER alignment for text.
</p>
<img src="imgs/textalign.jpg" class="tut" />
<a href="http://learningprocessing.com/examples/chp17/example-17-02-textalign"><strong>Example Text Align</strong></a>
<pre>
PFont f;
void setup() {
size(400,200);
f = createFont("Arial",16,true);
}
void draw() {
background(255);
stroke(175);
line(width/2,0,width/2,height);
textFont(f);
fill(0);
textAlign(CENTER);
text("This text is centered.",width/2,60);
textAlign(LEFT);
text("This text is left aligned.",width/2,100);
textAlign(RIGHT);
text("This text is right aligned.",width/2,140);
}
</pre>
<p class="txt">
<a href="http://processing.org/reference/textWidth_.html">textWidth()</a>—Calculates and returns the width of any character or text string.
</p><p class="txt">
Let's say we want to create a news ticker, where text scrolls across the bottom of the screen from left to right. When the news headline leaves the window, it reappears on the right hand side and scrolls again. If we know the x location of the beginning of the text and we know the width of that text, we can determine when it is no longer in view. textWidth() gives us that width.
</p><p class="txt">
To start, we declare headline, font, and x location variables, initializing them in setup().
</p>
<pre>
// A headline
String headline = "New study shows computer programming lowers cholesterol.";
PFont f; // Global font variable
float x; // horizontal location of headline
void setup() {
f = createFont("Arial",16,true); // Loading font
x = width; // initializing headline off-screen to the right
}
</pre>
<p class="txt">
In draw(), we display the text at the appropriate location.
</p>
<pre>
// Display headline at x location
textFont(f,16);
textAlign(LEFT);
text(headline,x,180);
</pre>
<p class="txt">
We change x by a speed value (in this case a negative number so that the text moves to the left.)
</p>
<pre>
// Decrement x
x = x - 3;
</pre>
<p class="txt">
Now comes more difficult part. It was easy to test when a circle reached the left side of the screen. We would simply ask: is x less than 0? With text, however, since it is left-aligned, when x equals zero, it is still viewable on screen. Instead, the text will be invisible when x is less than 0 minus the width of the text (See figure below). When that is the case, we reset x back to the right-hand side of the window, i.e. width.
</p><p class="txt">
<img src="imgs/textwidth.jpg" class="tut" />
</p>
<pre>
// If x is less than the negative width, then it is completely off the screen
float w = textWidth(headline);
if (x < -w) {
x = width;
}
</pre>
<p class="txt">
Here's the full example that displays a different headline each time the previous headline leaves the screen. The headlines are stored in a String array.
</p>
<pre>
<a href="http://learningprocessing.com/examples/chp17/example-17-03-scrollingtext"><strong>Example Scrolling Headlines</strong></a>
// An array of news headlines
String[] headlines = {
"Processing downloads break downloading record.",
"New study shows computer programming lowers cholesterol.",
};
PFont f; // Global font variable
float x; // horizontal location of headline
int index = 0;
void setup() {
size(400,200);
f = createFont("Arial",16,true);
// Initialize headline offscreen to the right
x = width;
}
void draw() {
background(255);
fill(0);
// Display headline at x location
textFont(f,16);
textAlign(LEFT);
text(headlines[index],x,180);
// Decrement x
x = x - 3;
// If x is less than the negative width,
// then it is off the screen
float w = textWidth(headlines[index]);
if (x < -w) {
x = width;
index = (index + 1) % headlines.length;
}
}
</pre>
<p class="txt">
In addition to textAlign() and textWidth(), Processing also offers the functions <a href="http://processing.org/reference/textLeading_.html">textLeading()</a>, <a href="http://processing.org/reference/textMode_.html">textMode()</a>, <a href="http://processing.org/reference/textSize_.html">textSize()</a> for additional display functionality.
</p>
<h3>Rotating text</h3>
<p class="txt"> <a href="http://processing.org/learning/transform2d/">Translation and rotation</a> can also be applied to text. For example, to rotate text around its center, translate to an origin point and use textAlign(CENTER) before displaying the text.
</p>
<pre>
<a href="http://learningprocessing.com/examples/chp17/example-17-05-rotatetext"><strong>Example: Rotating Text</strong></a>
PFont f;
String message = "this text is spinning";
float theta;
void setup() {
size(200, 200);
f = createFont("Arial",20,true);
}
void draw() {
background(255);
fill(0);
textFont(f); // Set the font
translate(width/2,height/2); // Translate to the center
rotate(theta); // Rotate by theta
textAlign(CENTER);
text(message,0,0);
theta += 0.05; // Increase rotation
}
</pre>
<h3>Displaying text character by character</h3>
<p class="txt">
In certain graphics applications, displaying text with each character rendered individually is required. For example, if each character needs to move or be colored independently then simply saying...
</p>
<pre>
text("a bunch of letters",0,0);
</pre>
<p class="txt">
...will not do.
</p>
<p class="txt">
The solution is to loop through a String, displaying each character one at a time.
</p>
<p class="txt">
Let's start by looking at an example that displays the text all at once.
</p>
<pre>
PFont f;
String message = "Each character is not written individually.";
void setup() {
size(400, 200);
f = createFont("Arial",20,true);
}
void draw() {
background(255);
fill(0);
textFont(f);
<strong>// Displaying a block of text all at once using text().</strong>
text(message,10,height/2);
}
</pre>
<p class="txt">
We can rewrite the code to display each character in loop, using the <a href="http://processing.org/reference/String_charAt_.html">charAt()</a> function.
</p>
<pre>
String message = "Each character is written individually.";
// The first character is at pixel 10.
int x = 10;
for (int i = 0; i < message.length(); i++) {
// Each character is displayed one at a time with the charAt() function.
text(message.charAt(i),x,height/2);
// All characters are spaced 10 pixels apart.
x += 10;
}
</pre>
<p class="txt">
Calling the <a href="http://processing.org/reference/text_.html">text()</a> function for each character will allow us more flexibility (for coloring, sizing, and placing characters within one String individually). The above code has a pretty major flaw, however—the x location is increased by 10 pixels for each character. Although this is approximately correct, because each character is not exactly ten pixels wide, the spacing is off.
</p>
<p class="txt">
The proper spacing can be achieved using the <a href="http://processing.org/reference/textWidth_.html">textWidth()</a> function as demonstrated in the code below. Note how this example achieves the proper spacing even with each character being a random size!
</p>
<img src="imgs/charbychar.jpg" class="tut" />
<pre>
PFont f;
String message = "Each character is written individually.";
void setup() {
size(400, 150);
f = createFont("Arial",20,true);
}
void draw() {
background(255);
fill(0);
textFont(f);
int x = 10;
for (int i = 0; i < message.length(); i++) {
textSize(random(12,36));
text(message.charAt(i),x,height/2);
<strong></strong>// textWidth() spaces the characters out properly.</strong>
x += textWidth(message.charAt(i));
}
noLoop();
}
</pre>
<p class="txt">
This "letter by letter" methodology can also be applied to a sketch where characters from a String move independently of one another. The following example uses object-oriented design to make each character from the original String a Letter object, allowing it to both be a displayed in its proper location as well as move about the screen individually.
</p>
<pre>
<a href="http://learningprocessing.com/examples/chp17/example-17-06-textbreakingup"><strong>Example Text breaking up</strong></a>
PFont f;
String message = "click mouse to shake it up";
// An array of Letter objects
Letter[] letters;
void setup() {
size(260, 200);
// Load the font
f = createFont("Arial",20,true);
textFont(f);
// Create the array the same size as the String
letters = new Letter[message.length()];
// Initialize Letters at the correct x location
int x = 16;
for (int i = 0; i < message.length(); i++) {
letters[i] = new Letter(x,100,message.charAt(i));
x += textWidth(message.charAt(i));
}
}
void draw() {
background(255);
for (int i = 0; i < letters.length; i++) {
// Display all letters
letters[i].display();
// If the mouse is pressed the letters shake
// If not, they return to their original location
if (mousePressed) {
letters[i].shake();
} else {
letters[i].home();
}
}
}
// A class to describe a single Letter
class Letter {
char letter;
// The object knows its original "home" location
float homex,homey;
// As well as its current location
float x,y;
Letter (float x_, float y_, char letter_) {
homex = x = x_;
homey = y = y_;
letter = letter_;
}
// Display the letter
void display() {
fill(0);
textAlign(LEFT);
text(letter,x,y);
}
// Move the letter randomly
void shake() {
x += random(-2,2);
y += random(-2,2);
}
// Return the letter home
void home() {
x = homex;
y = homey;
}
}
</pre>
<p class="txt">
The character by character method also allows us to display text along a curve. Before we move on to letters, let's first look at how we would draw a series of boxes along a curve. This example makes heavy use of <a href="http://www.processing.org/learning/trig/">Trignometry</a>.
</p>
<img src="imgs/boxes.jpg" class="tut" />
<a href="http://learningprocessing.com/examples/chp17/example-17-07-boxesoncurve"><strong>Example Boxes along a curve</strong></a>
<pre>
PFont f;
// The radius of a circle
float r = 100;
// The width and height of the boxes
float w = 40;
float h = 40;
void setup() {
size(320, 320);
smooth();
}
void draw() {
background(255);
// Start in the center and draw the circle
translate(width / 2, height / 2);
noFill();
stroke(0);
// Our curve is a circle with radius r in the center of the window.
ellipse(0, 0, r*2, r*2);
// 10 boxes along the curve
int totalBoxes = 10;
// We must keep track of our position along the curve
float arclength = 0;
// For every box
for (int i = 0; i < totalBoxes; i++) {
// Each box is centered so we move half the width
arclength += w/2;
// Angle in radians is the arclength divided by the radius
float theta = arclength / r;
pushMatrix();
// Polar to cartesian coordinate conversion
translate(r*cos(theta), r*sin(theta));
// Rotate the box
rotate(theta);
// Display the box
fill(0,100);
rectMode(CENTER);
rect(0,0,w,h);
popMatrix();
// Move halfway again
arclength += w/2;
}
}
</pre>
<p class="txt">
What we need to do is replace each box with a character from a String that fits inside the box. And since characters all do not have the same width, instead of using a variable "w" that stays constant, each box will have a variable width along the curve according to the textWidth() function.
</p>
<img src="imgs/textcurve.jpg" class="tut" />
<pre>
<a href="http://www.learningprocessing.com/examples/chapter-17/example-17-8/"><strong>Example Characters along a curve</strong></a>
// The message to be displayed
String message = "text along a curve";
PFont f;
// The radius of a circle
float r = 100;
void setup() {
size(320, 320);
f = createFont("Georgia",40,true);
textFont(f);
// The text must be centered!
textAlign(CENTER);
smooth();
}
void draw() {
background(255);
// Start in the center and draw the circle
translate(width / 2, height / 2);
noFill();
stroke(0);
ellipse(0, 0, r*2, r*2);
// We must keep track of our position along the curve
float arclength = 0;
// For every box
for (int i = 0; i < message.length(); i++)
{
// Instead of a constant width, we check the width of each character.
char currentChar = message.charAt(i);
float w = textWidth(currentChar);
// Each box is centered so we move half the width
arclength += w/2;
// Angle in radians is the arclength divided by the radius
// Starting on the left side of the circle by adding PI
float theta = PI + arclength / r;
pushMatrix();
// Polar to cartesian coordinate conversion
translate(r*cos(theta), r*sin(theta));
// Rotate the box
rotate(theta+PI/2); // rotation is offset by 90 degrees
// Display the character
fill(0);
text(currentChar,0,0);
popMatrix();
// Move halfway again
arclength += w/2;
}
}
</pre>
<p class="txt">
<em>Special thanks to <a href="http://ariel.chronotext.org/">Ariel Malka</a> for his advice on this last curved text example.</em>
</p>
</td>
</tr>
</table>