WPF эквивалентный TextRenderer - PullRequest
14 голосов
/ 05 мая 2009

Я использовал TextRenderer, чтобы измерить длину строки и, следовательно, изменить размер элемента управления соответствующим образом. Есть ли эквивалент в WPF или я могу просто использовать TextRendered.MeasureString?

Ответы [ 2 ]

20 голосов
/ 08 мая 2009

Спасибо, Гишу,

Читая ваши ссылки, я пришел к следующему, оба из которых делают за меня работу:

    /// <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);
    }
4 голосов
/ 05 мая 2009

Взгляните на класс FormattedText

Если вам нужно более детальное управление, вам нужно перейти к элементу AdvanceWidths типа GlyphTypeface. Нашел подобное обсуждение здесь с фрагментом кода, который выглядит так, как будто он может работать.

Обновление : похоже, это может быть дубликат Измерение текста в WPF .. OP, пожалуйста, подтвердите.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...