Font::getStringWidthFloat() with newLine(s)


Font::getStringWidthFloat() doesn’t account for newLines in the String…

I came up with a quick mod… I’m sure you can improve on it…

 float Font::getStringWidthFloat (const String& text) const
     String szLongestString = text;

     if (text.contains (newLine))
         StringArray szArray;
         szArray.addLines (text);
         szLongestString = String();
         for (int i = 0; i < szArray.size(); ++i)
             String szLine = szArray.getReference (i);
             if (szLine.length() > szLongestString.length())
                 szLongestString = szLine;

     float w = getTypeface()->getStringWidth (szLongestString);

     if (font->kerning != 0)
         w += font->kerning * szLongestString.length();

     return w * font->height * font->horizontalScale;


Font::getStringWidth on non-message thread

I’m not really sure if this is the right thing to do when there’s a newline in the string… What’s the context in which you’re having a problem with it?

Normally for non-trivial strings you’d want to measure it properly with something like GlyphArrangement or TextLayout rather that hitting these low-level functions. If we’ve used getTextWidth() internally in a place where we should have used something else, then we should change the calling code rather than this function.


My use case is to draw a rounded rectangle background for a Label which is showing info about the loaded sample in my VI when the mouse is over an instrument on The Stage:

 void CStageComponent::paint (Graphics& g)
     if (m_bShowingInfo)
         g.setColour (Colours::black);
         g.setOpacity (0.75f);
         const Font f = m_InfoFont.getFont();
         g.fillRoundedRectangle (14.0f, (float) getHeight() - 55.0f, f.getStringWidthFloat (m_InfoDisplay.getText()) + 30.0f, 50.0f, 4.0f);

I’d expect getStringWidthFloat() to account for the new lines or change the API docs to let us know that it doesn’t. I can’t think of any use case where the length should not account for the newLine?