Text 以编程方式测量Silverlight的文本字符串(以像素为单位)
在WPF中,System.Windows.Media命名空间中有格式化文本,我可以这样使用:Text 以编程方式测量Silverlight的文本字符串(以像素为单位),text,silverlight-4.0,fontmetrics,Text,Silverlight 4.0,Fontmetrics,在WPF中,System.Windows.Media命名空间中有格式化文本,我可以这样使用: private static Size GetTextSize(string txt, string font, int size, bool isBold) { Typeface tf = new Typeface(new System.Windows.Media.FontFamily(font), FontStyles.Normal,
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中,除了调用服务器外,还有没有一种很好的方法可以获得像素宽度(目前高度并不重要)?我见过一种方法,在您的特定实例中可能不起作用,就是将文本放入未设置样式的文本块中,然后获得该控件的宽度,如下所示:
private double GetTextWidth(string text, int fontSize)
{
TextBlock txtMeasure = new TextBlock();
txtMeasure.FontSize = fontSize;
txtMeasure.Text = text;
double width = txtMeasure.ActualWidth;
return width;
}
毫无疑问,这是一个黑客攻击。+1,但请记住在获得实际宽度之前使测量和排列无效。不幸的是,此解决方案在实际文本的上方和下方都有很小的边距。