Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I measure the Text Size in UWP Apps?

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?

like image 367
Domysee Avatar asked Mar 13 '16 10:03

Domysee


3 Answers

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.

like image 191
Domysee Avatar answered Sep 22 '22 19:09

Domysee


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

like image 22
testing Avatar answered Sep 23 '22 19:09

testing


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.

like image 30
Post Impatica Avatar answered Sep 25 '22 19:09

Post Impatica