【问题标题】:WPF equivalent to TextRendererWPF 等效于 TextRenderer
【发布时间】:2009-05-05 10:31:17
【问题描述】:

我使用TextRenderer 来测量字符串的长度,从而适当地调整控件的大小。 WPF 中是否有等价物或者我可以简单地使用TextRendered.MeasureString?

【问题讨论】:

    标签: c# .net wpf


    【解决方案1】:

    谢谢吉舒,

    阅读您的链接后,我想到了以下两种方法:

        /// <summary>
        /// Get the required height and width of the specified text. Uses FortammedText
        /// </summary>
        public static Size MeasureTextSize(string text, FontFamily fontFamily, FontStyle fontStyle, FontWeight fontWeight, FontStretch fontStretch, double fontSize)
        {
            FormattedText ft = new FormattedText(text,
                                                 CultureInfo.CurrentCulture,
                                                 FlowDirection.LeftToRight,
                                                 new Typeface(fontFamily, fontStyle, fontWeight, fontStretch),
                                                 fontSize,
                                                 Brushes.Black);
            return new Size(ft.Width, ft.Height);
        }
    
        /// <summary>
        /// Get the required height and width of the specified text. Uses Glyph's
        /// </summary>
        public static Size MeasureText(string text, FontFamily fontFamily, FontStyle fontStyle, FontWeight fontWeight, FontStretch fontStretch, double fontSize)
        {
            Typeface typeface = new Typeface(fontFamily, fontStyle, fontWeight, fontStretch);
            GlyphTypeface glyphTypeface;
    
            if(!typeface.TryGetGlyphTypeface(out glyphTypeface))
            {
                return MeasureTextSize(text, fontFamily, fontStyle, fontWeight, fontStretch, fontSize);
            }
    
            double totalWidth = 0;
            double height = 0;
    
            for (int n = 0; n < text.Length; n++)
            {
                ushort glyphIndex = glyphTypeface.CharacterToGlyphMap[text[n]];
    
                double width = glyphTypeface.AdvanceWidths[glyphIndex] * fontSize;
    
                double glyphHeight = glyphTypeface.AdvanceHeights[glyphIndex]*fontSize;
    
                if(glyphHeight > height)
                {
                    height = glyphHeight;
                }
    
                totalWidth += width;
            }
    
            return new Size(totalWidth, height);
        }
    

    【讨论】:

      【解决方案2】:

      看看FormattedText class

      如果您需要更精细的控制,则需要下降到 GlyphTypeface 类型的 AdvanceWidths 成员。在这里找到了一个similar discussion,代码 sn-p 看起来可行。

      更新:看起来这可能是 Measuring text in WPF 的副本。请确认。

      【讨论】:

        猜你喜欢
        • 2011-08-22
        • 2013-03-27
        • 1970-01-01
        • 2011-03-23
        • 2021-05-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多