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
How to Combine More Than Two Generic Lists in C# Zip
Editing Dictionary Values in a Foreach Loop
Foreach VS Somelist.Foreach(){}
Dictionary Returning a Default Value If the Key Does Not Exist
Understanding Async/Await in C#
Display Image from Database in Asp MVC
How to Get an Oauth 2.0 Authentication Token in C#
ASP.NET MVC Ambiguous Action Methods
C# - Approach for Saving User Settings in a Wpf Application
Web API Put Request Generates an Http 405 Method Not Allowed Error
Task Parallel Library Replacement for Backgroundworker
How to Write Some Data to Excel File(.Xlsx)
Embedding One Dll Inside Another as an Embedded Resource and Then Calling It from My Code
How to Automatically Scroll to the Bottom of a Multiline Text Box