【问题标题】:Programmatically measure text string in pixels for Silverlight以编程方式测量 Silverlight 的文本字符串(以像素为单位)
【发布时间】:2011-06-21 11:33:39
【问题描述】:

在 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 中是否有一种以像素为单位获取宽度的好方法(目前高度并不重要)?

【问题讨论】:

    标签: text silverlight-4.0 fontmetrics


    【解决方案1】:

    我见过的一种可能不适用于您的特定实例的方法是将文本放入无样式的 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,但请记住在获取实际宽度之前使度量和排列无效。
    • 不幸的是,此解决方案在实际文本上方和下方的边距很小。
    猜你喜欢
    • 2021-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-14
    相关资源
    最近更新 更多