使用WPF,测量大量短字符串的最有效方法是什么?具体来说,我想确定每个字符串的显示高度,给定统一格式(相同的字体,大小,重量等)和字符串可能占用的最大宽度?
Dan*_*ker 13
最低级别的技术(因此为创造性优化提供最大范围)是使用GlyphRuns.
它没有很好的记录,但我在这里写了一个小例子:
http://smellegantcode.wordpress.com/2008/07/03/glyphrun-and-so-forth/
该示例将字符串的长度计算为渲染之前的必要步骤.
在WPF中:
记得在读取DesiredSize属性之前调用TextBlock上的Measure().
如果TextBlock是即时创建的,但尚未显示,则必须先调用Measure(),如下所示:
MyTextBlock.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));
return new Size(MyTextBlock.DesiredSize.Width, MyTextBlock.DesiredSize.Height);
Run Code Online (Sandbox Code Playgroud)
在Silverlight中:
无需衡量.
return new Size(TextBlock.ActualWidth, TextBlock.ActualHeight);
Run Code Online (Sandbox Code Playgroud)
完整的代码如下所示:
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
}
Run Code Online (Sandbox Code Playgroud)