在Silverlight中以像素为单位编程测量文本字符串

17

在WPF中,有一个位于System.Windows.Media命名空间下的FormattedText MSDN FormattedText 可以这样使用:

private static Size GetTextSize(string txt, string font, int size, bool isBold)
{
   Typeface tf = new Typeface(new System.Windows.Media.FontFamily(font),
                             FontStyles.Normal,
                             (isBold) ? FontWeights.Bold : FontWeights.Normal,
                             FontStretches.Normal);
   FormattedText ft = new FormattedText(txt, new CultureInfo("en-us"), System.Windows.FlowDirection.LeftToRight, tf, (double)size, System.Windows.Media.Brushes.Black, null, TextFormattingMode.Display);
   return new Size { Width = ft.WidthIncludingTrailingWhitespace, Height = ft.Height };
}

除了向服务器发出请求之外,Silverlight 中获取像素宽度的好方法是什么(目前高度不重要)?

1个回答

30

一个我曾见过使用的方法,可能在你的特定情况下不适用,是将文本放入一个未经样式化的TextBlock中,然后获取该控件的宽度,方法如下:

private double GetTextWidth(string text, int fontSize)
{
    TextBlock txtMeasure = new TextBlock();
    txtMeasure.FontSize = fontSize;
    txtMeasure.Text = text;
    double width = txtMeasure.ActualWidth;
    return width;
}

这是一种hack方法,毫无疑问。


+1,但在获取实际宽度之前,请记得使测量无效并进行排列。 - Dr. Andrew Burnett-Thompson
很遗憾,这个解决方案在实际文本上方和下方的边距很小。 - Clément

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接