How to get accurate text width?

I have a label which I am trying to put a gray rectangle behind. To set the width of the background rectangle, I need to get the width of the text, so I'm doing:

backgroundWidth = myLabel->getFont().getStringWidthFloat(myLabel->getText()) + 30 /*padding*/;

And drawing the background as:

g.setColour(Colour(0x4c14181b));
g.fillRoundedRectangle(33.0f, 265.0f, backgroundWidth, 28.0f, 14.000f);

I'm not changing the font anywhere, it's just set in the constructor and is generated code.

What I'm getting back is a width which is roughly the size of the text, but is inconsistently is too big or small depending on the string. For example, the string "000000" will have a background rectangle which extends 50px after the last character, and the string "111111" has a background rect which only extends 5px after the last character. Is this a bug or am I misusing `getStringWidthFloat`?

1 Like

Most likely the font you're using to measure it is different to the one that's actually used to draw it. The Label class will scale its font to fit, so that's probably what's happening here.

1 Like