I seem to have encountered a text position bug using the text() function to draw text to PGraphic. My hope was to use Processing to generate transparent png images from a text file for use in an iPhone application I'm developing. The reason I'm creating these as images is that there is no iPhone support for formatted (multicolor) text strings, so I'd hoped to just load in a series of transparent pngs that I'd saved from Processing.
This all works fine when saving from the normal drawing window (minus the background transparency, of course). However, when I move everything into a PGraphic, the text position gets thrown off with each new text() call and the letter spacing and kerning becomes horribly unpredictable. Most notably, the text from subsequent text() commands tends to overlap the previous command. The problem seems independent of the native fonts hinting, textMode(), and loadFont() vs. createFont().
Here's the basic idea of the code:
Code:
String[] terms = { "|f|ee", "f|i|e", "fo|e|", "f|u|m"}; // pipe characters indicate highlight start/stop
PFont arialB;
color hl = color(41,171,226); // highlighted text in blue
color nl = color(0); // normal text in black
int t = 0;
PGraphics pg;
void setup() {
size(90,20);
smooth();
arialB = createFont("Arial-BoldMT", 14);
//terms = loadStrings(filePath);
noStroke();
pg = createGraphics(width,height,JAVA2D);
pg.hint(ENABLE_NATIVE_FONTS);
pg.smooth();
pg.noStroke();
pg.textFont(arialB);
}
void draw() {
if(t < terms.length) {
pg.beginDraw();
pg.background(255,0);
int hlStart = terms[t].indexOf("|");
int hlStop = terms[t].indexOf("|",hlStart+1);
String noTokens = join(split(terms[t],"|"),"");
float tWidth = pg.textWidth(noTokens);
float startX = pg.width/2-tWidth/2;
float startY = pg.height/2+pg.textAscent()/2;
// if highlighted area occurs at beginning of word
if(hlStart==0) {
String part1 = terms[t].substring(hlStart+1,hlStop);
String part2 = terms[t].substring(hlStop+1,terms[t].length());
pg.fill(hl);
pg.text(part1,startX,startY);
pg.fill(nl);
pg.text(part2);
}
// if highlighted area occurs at end of word
else if(hlStop == terms[t].length()-1) {
String part1 = terms[t].substring(0,hlStart);
String part2 = terms[t].substring(hlStart+1,hlStop);
pg.fill(nl);
pg.text(part1,startX,startY);
pg.fill(hl);
pg.text(part2);
}
// if highlighted area occurs in middle of word
else {
String part1 = terms[t].substring(0,hlStart);
String part2 = terms[t].substring(hlStart+1,hlStop);
String part3 = terms[t].substring(hlStop+1,terms[t].length());
pg.fill(nl);
pg.text(part1,startX,startY);
pg.fill(hl);
pg.text(part2);
pg.fill(nl);
pg.text(part3);
}
pg.endDraw();
pg.save("output/"+noTokens+".png");
t++;
}
else {
println("DONE!");
exit();
}
}
I've been really frustrated by this and would greatly appreciate any help anyone might offer.
Thanks!