[Solved] getStringWidthFloat returns wrong width

It seems, that the function Font::getStringWidthFloat() returns a width, which is too short.

See also attached screenshot.

Here is my code excerpt:

void MainContentComponent::resized()
{
    label1.setText("This is a test string.", NotificationType::dontSendNotification);
    label2.setText("This is a test string.", NotificationType::dontSendNotification);
    
    Font myFont(16, Font::plain);
    label1.setFont(myFont);
    label2.setFont(myFont);

    int label1Width = (int) myFont.getStringWidthFloat(label1.getText());

    label1.setBounds(10, 100, label1Width, 25);
    label2.setBounds(10, 140, 200,         25);
}

I create two labels, with the same text. The first label gets its width from getStringWidthFloat(). To the second label I assigned a width by hand, which gives more than enough room for the text string. I had expected, that both labels should have equally long text. But that is not the case. The text of label1 is squeezed together, indicating that the size returned by getStringWidthFloat is too short.

PS: I have also attached the source code for my testproject. (see the three source files)

I am using JUCE 4 on Windows 7 and VS2015 Express

1 Like

labels have a border gap around the text, so you'd need to allow some space for that?

1 Like

Ah! That explains it. Thanks.

Edit: just tested: indeed, after taking the border into account the two text widths line up. :-)

Why isn’t there a method for label for the required width? Like TextButtons's getBestWidthForHeight?

1 Like