How can I measure the Text Size in UWP Apps?

2020-02-10 03:39发布

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?

3条回答
SAY GOODBYE
2楼-- · 2020-02-10 04:16

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.

查看更多
兄弟一词,经得起流年.
3楼-- · 2020-02-10 04:22

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.

查看更多
甜甜的少女心
4楼-- · 2020-02-10 04:26

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

查看更多
登录 后发表回答