In WPF, this was possible using FormattedText, like this:
private Size MeasureString(string candidate)
{
var formattedText = new FormattedText(
candidate,
CultureInfo.CurrentUICulture,
FlowDirection.LeftToRight,
new Typeface(this.textBlock.FontFamily, this.textBlock.FontStyle, this.textBlock.FontWeight, this.textBlock.FontStretch),
this.textBlock.FontSize,
Brushes.Black);
return new Size(formattedText.Width, formattedText.Height);
}
But in UWP this class does not exist any more. So how is it possible to calculate text dimensions in universal windows platform?
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.
Here is an alternative approach using Win2D:
private Size MeasureTextSize(string text, CanvasTextFormat textFormat, float limitedToWidth = 0.0f, float limitedToHeight = 0.0f)
{
var device = CanvasDevice.GetSharedDevice();
var layout = new CanvasTextLayout(device, text, textFormat, limitedToWidth, limitedToHeight);
var width = layout.DrawBounds.Width;
var height = layout.DrawBounds.Height;
return new Size(width, height);
}
You can use it like this:
string text = "Lorem ipsum dolor sit amet";
CanvasTextFormat textFormat = new CanvasTextFormat
{
FontSize = 16,
WordWrapping = CanvasWordWrapping.WholeWord,
};
Size textSize = this.MeasureTextSize(text, textFormat, 320.0f);
Source
If you are having issues in UWP with Size not resolving or working properly with double's. It is probably because you are using System.Drawing.Size.
Use Windows.Foundation.Size instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With