How to get string width with font-fallback?

When trying to use font.getStringWidthFloat with characters in the string that are not contained within the font (e.g. emojis) the returned width is incorrect.

I guess the getStringWidthFloat function doesn’t consider characters not included in the font and thus returns the width of the standard □ glyph instead of the emoji one?

juce::String	hvStr = u8"⚡";
auto width = font.getStringWidthFloat ( hvStr );
auto b = getLocalBounds ().toFloat ().withWidth ( width );
g.drawText ( hvStr, b, juce::Justification::centredLeft, false );

This draws nothing. If I multiply the width by 2.5f, then it draws the emoji.

1 Like

IIRC, you can render the text to a juce::TextLayout and then query its width and height to get the required bounds.

Although that’s very much a workaround

I mean, this kind of makes sense, doesn’t it? “What is the width of something that doesn’t exist?” might be asked, but then also “Should □ be used to indicate something doesn’t exist?” should also probably be asked.

Either way, this sounds like intended behaviour. Why get the width of something that won’t be rendered as intended, in the first place?

You don’t seem to be aware that JUCE8 does indeed render the output as intended. They have a fallback mechanism that renders characters not supported by a font, with specific fallback fonts (e.g. emoji-font for Windows/Mac when you use an emoji, etc.)

So it’s expected that a function that is supposed to return the width of a string in pixels, uses the same fallback mechanism and returns the correct width. Otherwise, that function would now be completely useless and should be deprecated and an alternative should be offered.

1 Like