如何衡量UWP应用中的文字大小?

Dom*_*see 13 c# win-universal-app uwp

在WPF中,这可以使用FormattedText,如下所示:

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);
}
Run Code Online (Sandbox Code Playgroud)

但是在UWP中,这个类不再存在了.那么如何在通用Windows平台中计算文本尺寸呢?

Dom*_*see 29

在UWP中,您创建一个TextBlock,设置其属性(如Text,FontSize),然后调用其Measure方法并传入无限大小.

var tb = new TextBlock { Text = "Text", FontSize = 10 };
tb.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));
Run Code Online (Sandbox Code Playgroud)

之后,它的DesiredSize属性包含TextBlock将具有的大小.

  • @Reddy我不是那么快(虽然我希望我是).在提问时,有一个"回答你自己的问题"复选框.我这样做是因为我没有在SO上找到任何关于这个问题的问题或答案,所以其他人会找到它(希望如此)并且不必搜索它的时间. (5认同)
  • 请注意,这不是UWP特有的.它也适用于WPF或Silverlight. (3认同)

tes*_*ing 5

这是使用 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);
}
Run Code Online (Sandbox Code Playgroud)

你可以这样使用它:

string text = "Lorem ipsum dolor sit amet";

CanvasTextFormat textFormat = new CanvasTextFormat
{
    FontSize = 16,
    WordWrapping = CanvasWordWrapping.WholeWord,
};

Size textSize = this.MeasureTextSize(text, textFormat, 320.0f);
Run Code Online (Sandbox Code Playgroud)

来源