textWidth() returns wrong width

The textWidth () function returns an invalid value. Is there any way to fix it?
The screenshot shows that the line is longer than the text.

code:

String str="jjjjjjjjjjjjjjjjjjjj";




void setup(){
  
}

void draw(){
  background(255);
  
  textSize(93);
  fill(0);
  text(str,50,500);
  strokeWeight(3);
  line(50,600,50+textWidth(str),600);
}

Thanks in advance!

Actually, there is a consistent deviation, not an invalid one, depending on the font size. I had this kind of issue. You can fix it by subtracting a multiplier depending on the font size. If you use a font other than the default font, you need to change this multiplier. You can determine the most appropriate value by trial and error. For your case;
float delta = 93 * 0.08;
line(50,600,50+textWidth(str) - delta, 600);

In my experience it works better when you use
createFont and setFont so the text is defined

3 Likes

Thanks for the reply.
I experimented with different fonts and different text. Unfortunately with some fonts textWidth() still doesn’t work well.

Code:

String str="Hello! I am AniMan Otaku, and I love Rikka Takanashi so much!";
PFont font;
String fontName="Monospaced";


void setup(){
  font=createFont(fontName,36);
  textFont(font);
  printArray(PFont.list());
  /*
    don't work well: 
    
    SansSerif
    SansSerif-Bold
    Serif
    Serif-Bold
  */
}

void draw(){
  background(255);
  
  fill(0);
  text(str,50,500);
  strokeWeight(3);
  line(50,600,50+textWidth(str),600);
}



void mouseDragged(){
  
  if(mouseX/5f>0)
  font=createFont(fontName,mouseX/10f);
  textFont(font);
}

And I’m wondering if Serif, SansSerif, Monospaced are the fonts installed on my phone, or are they the standard processing fonts?