How to resize label such that text exactly fits?

To make a label nicely fit in the layout I would like to set its size such that the text inside the label exactly fits. So I do this:

    // create components
    mSliderLabel.setText("Sine", juce::NotificationType::dontSendNotification);
    mSliderLabel.setColour(juce::Label::textColourId, juce::Colours::orange);

void TestGeneratorComponent::resized()
    auto area = getLocalBounds();
    auto topBar = area.removeFromTop(28);
    auto sineBar = area.removeFromTop(28);

So I try to set the size of the label to the needed width. But this is not working. Label size seems zero.
How can I get the size needed for some label?

i once made a video about the opposite problem, resizing a text to maximize some label’s bounds. maybe you can invert some of these processes:

This is not going to work. mSliderLabel has no width at that point. You are trying to give it a width by getting the width. (Setting text into a label doesn’t automatically set the width. It will be 0 at this point.) Try this:

    auto font = mSliderLabel.getFont();
    auto w = font.getStringWidth(mSliderLabel.getText());

You can get the width required to display some text via the Font:

This works more or less.
The text does not seem to fit. I need to add a few pixels. See the picture below where I show the result by adding 0, 2, 4, 6 and 8 to the width respectively.

As you can see, at +0 the string does not fit. At +2 it fits, but the text seems sqeezed a bit.
So the question now is, how do I know how much to add to make it perfectly fit?

Yeah, some of this is dependent on the font you are using and some of the characteristics of the font. For example, you can control whether the font gets squished or not to fit by using setDefaultMinimumHorizontalScaleFactor() on the font. If I remember, .7f is the default setting, which allows up to 70% squishing, but setting this to 1.0f will remove any squishing - which is how I have my fonts set.

You might want to use getStringWidthFloat() and round it up to the next int.

Otherwise, I’m not sure why you are getting those results - this works for me.

Oh… one other thing. The Label has a default amount of margin on it. That’s probably what the issue is. Let me see if I can find where that is set.

Edit: Right, it’s Label::setBorderSize(). So you might want to do this:

        mSliderLabel.setBorderSize( {0,0,0,0} );    // get rid of extra space - t,l,b,r

Alternately, you could use getBorderSize() and add the left and right margins to your width.

1 Like

That (setting border to zero) worked!