在WPF中测量文本

时间:2009-03-10 21:54:32

标签: wpf formatting

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

4 个答案:

答案 0 :(得分:13)

最低级别的技术(因此为创造性优化提供最大范围)是使用GlyphRuns。

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

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

该示例在渲染之前计算出字符串的长度作为必要步骤。

答案 1 :(得分:6)

非常简单,并且由FormattedText类完成! 试试吧。

答案 2 :(得分:6)

在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 :(得分:3)

您可以在渲染的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%的准确度