Loading...
Logo
Processing Forum
considering a font, a size of that font, is there a way to calculate the size in pixel of a word written with this font ?

Replies(6)

look at textwidth() in ref pages.

is there a native way to make the opposite ? 
(I mean find the right font size to make the text pixel width match a particular width)
trial and error... something like this maybe

Copy code
  1. int getSize(String str, float maxWidth){
  2.    for (int i=1; i<200;i++){
  3.             textSize(i);
  4.       float sw = textWidth(str);
  5.             if (sw>maxWidth){
  6.                 return i;
  7.             }
  8.    }
  9.    return -1; // some error
  10. }
was using that one and you comfort me that there isn't probably other stuff coming native :)

thanks rsksmiles :)
I think this might be a better way than trying random sizes. You could also put this into a function...

PFont font;

void setup() {
  size(500, 500);
  font = loadFont("SourceSansPro-Regular-50.vlw");
}

void draw() {
  background(255);
  
  fill(0);
  textFont(font);

  float fitWidth = mouseX;   // use the mouse as the "width"
  String text = "Rabbits";   // text we want to write
  
  // calculate the text width at full size (50px in this case)
  float baseWidth = textWidth(text);  
  float targetSize = fitWidth / baseWidth * font.getSize();  // size to fit
  
  textSize(targetSize);
  text(text, 0, height * 0.5);
}