在WPF中,我可以这样使用System.Windows.Media名称空间MSDN FormattedText中的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中有没有一个很好的方法来获取像素宽度(此时高度并不重要)?
发布于 2011-02-05 00:34:45
我见过的一种方法是将文本放入一个未设置样式的TextBlock中,然后获取该控件的宽度,如下所示:
private double GetTextWidth(string text, int fontSize)
{
TextBlock txtMeasure = new TextBlock();
txtMeasure.FontSize = fontSize;
txtMeasure.Text = text;
double width = txtMeasure.ActualWidth;
return width;
}
毫无疑问,这是个黑客行为。
https://stackoverflow.com/questions/4900316
复制相似问题