How can I measure the Text Size in UWP Apps?

后端 未结 3 453
后悔当初
后悔当初 2020-12-14 19:50

In WPF, this was possible using FormattedText, like this:

private Size MeasureString(string candidate)
{
    var formattedText = new FormattedText(
        c         


        
相关标签:
3条回答
  • 2020-12-14 20:04

    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.

    0 讨论(0)
  • 2020-12-14 20:08

    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.

    0 讨论(0)
  • 2020-12-14 20:27

    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

    0 讨论(0)
提交回复
热议问题