微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

以编程方式测量Silverlight的文本字符串(以像素为单位)

在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中是否有一个很好的方法获取像素的宽度(当时高度不重要)

解决方法

我所看到的一种方法,可能在您的特定实例中可能无法正常工作,是将文本投射到一个未分层的TextBlock中,然后获取该控件的宽度,如下所示:

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

这是一个黑客,毫无疑问。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐