How to Calculate Wpf Textblock Width for Its Known Font Size and Characters

How to calculate WPF TextBlock width for its known font size and characters?

Use the FormattedText class.

I made a helper function in my code:

private Size MeasureString(string candidate)
{
var formattedText = new FormattedText(
candidate,
CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
new Typeface(this.textBlock.FontFamily, this.textBlock.FontStyle, this.textBlock.FontWeight, this.textBlock.FontStretch),
this.textBlock.FontSize,
Brushes.Black,
new NumberSubstitution(),
1);

return new Size(formattedText.Width, formattedText.Height);
}

It returns device-independent pixels that can be used in WPF layout.

Measuring text in WPF

The most low-level technique (and therefore giving the most scope for creative optimisations) is to use GlyphRuns.

It's not very well documented but I wrote up a little example here:

http://smellegantcode.wordpress.com/2008/07/03/glyphrun-and-so-forth/

The example works out the length of the string as a necessary step before rendering it.

How can I measure the Text Size in UWP Apps?

In UWP, you create a TextBlock, set its properties (like Text, FontSize), and then call its Measure method and pass in infinite size.

var tb = new TextBlock { Text = "Text", FontSize = 10 };
tb.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));

After that its DesiredSize property contains the size the TextBlock will have.



Related Topics



Leave a reply



Submit