【问题标题】:Measuring text in WPF在 WPF 中测量文本
【发布时间】:2009-03-10 21:54:32
【问题描述】:

使用 WPF,测量大量短字符串的最有效方法是什么?具体来说,我想确定每个字符串的显示高度,给定统一的格式(相同的字体、大小、粗细等)以及字符串可能占据的最大宽度?

【问题讨论】:

标签: wpf formatting


【解决方案1】:

最底层的技术(因此为创意优化提供了最大的空间)是使用 GlyphRuns。

没有很好的记录,但我在这里写了一个小例子:

http://smellegantcode.wordpress.com/2008/07/03/glyphrun-and-so-forth/

该示例计算出字符串的长度,这是渲染之前的必要步骤。

【讨论】:

  • 看起来这个例子没有考虑更复杂的概念,比如字距和标准连字,Daniel,你能确认一下吗(10 年后:))?
【解决方案2】:

在 WPF 中:

记得在读取 DesiredSize 属性之前调用 TextBlock 上的 Measure()。

如果 TextBlock 是即时创建的,但尚未显示,则必须先调用 Measure(),如下所示:

MyTextBlock.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));

return new Size(MyTextBlock.DesiredSize.Width, MyTextBlock.DesiredSize.Height);

在 Silverlight 中:

无需测量。

return new Size(TextBlock.ActualWidth, TextBlock.ActualHeight);

完整的代码如下所示:

public Size MeasureString(string s) {

    if (string.IsNullOrEmpty(s)) {
        return new Size(0, 0);
    }

    var TextBlock = new TextBlock() {
        Text = s
    };

#if SILVERLIGHT
    return new Size(TextBlock.ActualWidth, TextBlock.ActualHeight);
#else
    TextBlock.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));

    return new Size(TextBlock.DesiredSize.Width, TextBlock.DesiredSize.Height);
#endif
}

【讨论】:

    【解决方案3】:

    非常简单,由 FormattedText 类完成! 试试看。

    【讨论】:

    • FormattedText 在 UniversalWindows 中不可用,帮帮我!
    【解决方案4】:

    您可以在呈现的 TextBox 上使用 DesiredSize 属性来获取高度和宽度

    using System.Windows.Threading;
    
    ...
    
    Double TextWidth = 0;
    Double TextHeight = 0;
    ...
    
    MyTextBox.Text = "Words to measure size of";
    this.Dispatcher.BeginInvoke(
        DispatcherPriority.Background,
        new DispatcherOperationCallback(delegate(Object state) {
            var size = MyTextBox.DesiredSize;
            this.TextWidth = size.Width;
            this.TextHeight = size.Height;
            return null; 
        }
    ) , null);
    

    如果您有大量字符串,首先预先计算给定字体中每个单个字母和符号的高度和宽度可能会更快,然后根据字符串字符进行计算。由于字距调整等原因,这可能不是 100% 准确

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-23
      • 1970-01-01
      • 2011-05-04
      • 1970-01-01
      • 2010-09-24
      • 2013-06-13
      相关资源
      最近更新 更多