Deprecation of Font::getStringWidth

Can you clarify when to use GlyphArrangement vs TextLayout when replacing Font::getStringWidth. Is there any reason to prefer one over the other?

1 Like

It really depends on the method you’ll eventually use to draw the text. If you’re drawing with GlyphArrangement, then you should use GlyphArrangement for text measurement too.

I would assume that in most cases people just call g.drawText.

So how are we supposed to replace getStringWidth() when coupled with g.drawText()? What’s the correct new pattern please?
Thanks!

1 Like

Below is how I handled it.

const auto stringWidth{ juce::TextLayout::getStringWidth( juce::AttributedString(getName())) };
1 Like
const auto stringWidth{ juce::TextLayout::getStringWidth( juce::AttributedString(getName())) };

Well that’s a mouthful :slight_smile:

Graphics::drawText internally uses a GlyphArrangement to draw text, so you should use GlyphArrangement::getStringWidth to measure strings that will be drawn directly via Graphics.

2 Likes

Per @reuk 's instructions, my usage is;

const auto stringWidth{ juce::GlyphArrangement::getStringWidth(g.getCurrentFont(), juce::StringRef(getName())) };
1 Like

A word of warning: I just found out the hard way that there is a significant difference between Juce 7 juce::Font::getStringWidth() and Juce 8 juce::GlyphArrangement::getStringWidth() and juce::TextLayout::getStringWidth()

The Juce 7 call handles multi-line strings by returning the pixel width of the longest line while the Juce 8 new best practice ignores line breaks leading to a different result for multi-line strings.

The deprecated fallback code in Juce 8 does work like Juce 7.

It would be nice if this had been listed in breaking changes when getStringWidth() was deprecated.

	juce::Font f(juce::FontOptions(16.f));
	juce::String txt = "short line\nlong line long line long line";
	auto w1 = juce::GlyphArrangement::getStringWidthInt(f, txt);
	auto w2 = f.getStringWidth(txt);

This produces w1 = 67 and w2 = 240 with the default font.

5 Likes

juce 8 should probably not ignore line breaks though
as it should be like it would have been displayed

1 Like

This was a very handy feature. I think creating a full GlyphArrangement or TextLayout is an overkill just to try and figure out the text width.
I understand there were accuracy issues but isn’t it worth fixing instead of deprecating so we can have a quick and friendly way to fetch the width of our text?

Any chance of getting this one back?

3 Likes

thnks man