textHeight() function
in
Programming Questions
•
1 year ago
I'm trying to compute a textHeight function.
Could someone help with fine tuning, it should work a bit more corrrect with a smaller or bigger amount of text.
Also how is the height of the line spacing defined in processing? It's more then textAscent()+textDescent()
- void setup() {
- size(400, 400);
- String txt = "rolloverProject AANLEG MINI PARK CASAolloverProject AANLEG MINI PARK CASAolloverProject AANLEG MINI PARK CASA rolloverProject AANLEG MINI PARK CASA";
- textSize(24);
- textAlign(LEFT, TOP);
- float th = textHeight(txt, 300);
- fill(255, 0, 0);
- rect(20, 20, 300, th);
- fill(0);
- text(txt, 20, 20, 300, height);
- }
- float textHeight(String txt, float containerWidth) {
- String[] words = split(txt, " ");
- float row = 0;
- float x = 0;
- for(int i = 0; i < words.length; i++) {
- float tw = textWidth(words[i]);
- if(x + tw > containerWidth) {
- x = tw;
- row++;
- } else {
- x += tw;
- }
- }
- float lineSpacing = (textAscent()+textDescent())/2;
- return row*(textAscent()+textDescent()+lineSpacing);
- }
1