In WPF, this was possible using FormattedText, like this:
private Size MeasureString(string candidate)
{
var formattedText = new FormattedText(
c
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.
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.
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