FormattedText 类中的下标/上标?

发布于 2024-08-30 15:07:04 字数 131 浏览 5 评论 0原文

我正在使用 FormattedText 类创建文本 - 但是在使用此类时如何下标或上标文本?我找到了如何在使用 TextBlock 时执行此操作的解决方案,但我使用的是 FormattedText 而不是 TextBlock ):感谢您的任何提示!

I'm creating Text using the FormattedText class - but how can I subscript oder superscript Text when using this class? I found solution on how to do this when using a TextBlock, but I'm using FormattedText and not the TextBlock ): Thanks for any hint!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

您的好友蓝忘机已上羡 2024-09-06 15:07:04

FormattedText 无法执行下标/上标 - 但 TextFormatter 可以。

TextFormatter 是一个低级 API,您需要编写大量代码才能使用它 - 但大多数代码只是对用于传递格式化参数 int TextFormatter

如何使用 TextFormatter

TextFormatter 接受一个 TextSource 对象并生成多个 TextLine 对象(每一行一个),即 TextLine.Draw<然后可以使用 /code> 方法将线条绘制到绘图上下文。

TextSource 类是抽象的,您必须对其进行子类化并重写 GetTextRun 方法,该方法仅返回位于所提供的字符位置的 TextRun 对象。

TextRun 也是抽象的 - 但它确实有可以使用的子类 - 有趣的类是 TextCharacters ,它包含字符串和格式信息。

格式信息位于 TextRunProperties 对象中,不幸的是,这是您必须子类化的另一个抽象类。

TextRunProperties 具有 TextRunTypographyProperties 类型的 TypographyProperties 属性。

TextRunTypographyProperties 是您需要子类化的另一个抽象类。

最后,TextRunTypographyPropertiesVariants 属性,您可以像 TextBlock 示例一样使用。

代码示例

下面是我可以编写的用于绘制上标文本的最少代码:

首先,我们的 TextRunProperties 和 TextRunTypographyProperties 可以返回上标字体变体:

class CustomTextRunProperties : TextRunProperties
{
    private bool _superscript;
    public CustomTextRunProperties(bool superscript)
    {
        _superscript = superscript;
    }
    public override System.Windows.Media.Brush BackgroundBrush
    {
        get { return null; }
    }

    public override CultureInfo CultureInfo
    {
        get { return CultureInfo.CurrentCulture; }
    }

    public override double FontHintingEmSize
    {
        get { return 22; }
    }

    public override double FontRenderingEmSize
    {
        get { return 22; }
    }

    public override Brush ForegroundBrush
    {
        get { return Brushes.Black; }
    }

    public override System.Windows.TextDecorationCollection TextDecorations
    {
        get { return new System.Windows.TextDecorationCollection(); }
    }

    public override System.Windows.Media.TextEffectCollection TextEffects
    {
        get { return new TextEffectCollection(); }
    }

    public override System.Windows.Media.Typeface Typeface
    {
        get { return new Typeface("Calibri"); }
    }

    public override TextRunTypographyProperties TypographyProperties
    {
        get
        {
            return new CustomTextRunTypographyProperties(_superscript);
        }
    }

}

class CustomTextRunTypographyProperties : TextRunTypographyProperties
{
    private bool _superscript;

    public CustomTextRunTypographyProperties(bool superscript)
    {
        _superscript = superscript;
    }

    public override int AnnotationAlternates
    {
        get { return 0; }
    }

    public override bool CapitalSpacing
    {
        get { return false; }
    }

    public override System.Windows.FontCapitals Capitals
    {
        get { return FontCapitals.Normal; }
    }

    public override bool CaseSensitiveForms
    {
        get { return false; }
    }

    public override bool ContextualAlternates
    {
        get { return false; }
    }

    public override bool ContextualLigatures
    {
        get { return false; }
    }

    public override int ContextualSwashes
    {
        get { return 0; }
    }

    public override bool DiscretionaryLigatures
    {
        get { return false; }
    }

    public override bool EastAsianExpertForms
    {
        get { return false; }
    }

    public override System.Windows.FontEastAsianLanguage EastAsianLanguage
    {
        get { return FontEastAsianLanguage.Normal; }
    }

    public override System.Windows.FontEastAsianWidths EastAsianWidths
    {
        get { return FontEastAsianWidths.Normal; }
    }

    public override System.Windows.FontFraction Fraction
    {
        get { return FontFraction.Normal; }
    }

    public override bool HistoricalForms
    {
        get { return false; }
    }

    public override bool HistoricalLigatures
    {
        get { return false; }
    }

    public override bool Kerning
    {
        get { return true; }
    }

    public override bool MathematicalGreek
    {
        get { return false; }
    }

    public override System.Windows.FontNumeralAlignment NumeralAlignment
    {
        get { return FontNumeralAlignment.Normal; }
    }

    public override System.Windows.FontNumeralStyle NumeralStyle
    {
        get { return FontNumeralStyle.Normal; }
    }

    public override bool SlashedZero
    {
        get { return false; }
    }

    public override bool StandardLigatures
    {
        get { return false; }
    }

    public override int StandardSwashes
    {
        get { return 0; }
    }

    public override int StylisticAlternates
    {
        get { return 0; }
    }

    public override bool StylisticSet1
    {
        get { return false; }
    }

    public override bool StylisticSet10
    {
        get { return false; }
    }

    public override bool StylisticSet11
    {
        get { return false; }
    }

    public override bool StylisticSet12
    {
        get { return false; }
    }

    public override bool StylisticSet13
    {
        get { return false; }
    }

    public override bool StylisticSet14
    {
        get { return false; }
    }

    public override bool StylisticSet15
    {
        get { return false; }
    }

    public override bool StylisticSet16
    {
        get { return false; }
    }

    public override bool StylisticSet17
    {
        get { return false; }
    }

    public override bool StylisticSet18
    {
        get { return false; }
    }

    public override bool StylisticSet19
    {
        get { return false; }
    }

    public override bool StylisticSet2
    {
        get { return false; }
    }

    public override bool StylisticSet20
    {
        get { return false; }
    }

    public override bool StylisticSet3
    {
        get { return false; }
    }

    public override bool StylisticSet4
    {
        get { return false; }
    }

    public override bool StylisticSet5
    {
        get { return false; }
    }

    public override bool StylisticSet6
    {
        get { return false; }
    }

    public override bool StylisticSet7
    {
        get { return false; }
    }

    public override bool StylisticSet8
    {
        get { return false; }
    }

    public override bool StylisticSet9
    {
        get { return false; }
    }

    public override FontVariants Variants
    {
        get { return _superscript ? FontVariants.Superscript: FontVariants.Normal; }
    }
}

以及用于段落格式设置的类似类(取自 MSDN TextFormatter 示例):

class GenericTextParagraphProperties : TextParagraphProperties
{
    public GenericTextParagraphProperties(
       FlowDirection flowDirection,
       TextAlignment textAlignment,
       bool firstLineInParagraph,
       bool alwaysCollapsible,
       TextRunProperties defaultTextRunProperties,
       TextWrapping textWrap,
       double lineHeight,
       double indent)
    {
        _flowDirection = flowDirection;
        _textAlignment = textAlignment;
        _firstLineInParagraph = firstLineInParagraph;
        _alwaysCollapsible = alwaysCollapsible;
        _defaultTextRunProperties = defaultTextRunProperties;
        _textWrap = textWrap;
        _lineHeight = lineHeight;
        _indent = indent;
    }

    public override FlowDirection FlowDirection
    {
        get { return _flowDirection; }
    }

    public override TextAlignment TextAlignment
    {
        get { return _textAlignment; }
    }

    public override bool FirstLineInParagraph
    {
        get { return _firstLineInParagraph; }
    }

    public override bool AlwaysCollapsible
    {
        get { return _alwaysCollapsible; }
    }

    public override TextRunProperties DefaultTextRunProperties
    {
        get { return _defaultTextRunProperties; }
    }

    public override TextWrapping TextWrapping
    {
        get { return _textWrap; }
    }

    public override double LineHeight
    {
        get { return _lineHeight; }
    }

    public override double Indent
    {
        get { return _indent; }
    }

    public override TextMarkerProperties TextMarkerProperties
    {
        get { return null; }
    }

    public override double ParagraphIndent
    {
        get { return _paragraphIndent; }
    }

    private FlowDirection _flowDirection;
    private TextAlignment _textAlignment;
    private bool _firstLineInParagraph;
    private bool _alwaysCollapsible;
    private TextRunProperties _defaultTextRunProperties;
    private TextWrapping _textWrap;
    private double _indent;
    private double _paragraphIndent;
    private double _lineHeight;
}

现在 TextSource 实现:

public class CustomTextSourceRun
{
    public string Text;
    public bool IsSuperscript;
    public bool IsEndParagraph;
    public int Length { get { return IsEndParagraph ? 1 : Text.Length; } }
}


class CustomTextSource : TextSource
{
    public List<CustomTextSourceRun> Runs = new List<CustomTextSourceRun>();

    public override TextRun GetTextRun(int textSourceCharacterIndex)
    {
        int pos = 0;
        foreach (var currentRun in Runs)
        {
            if (textSourceCharacterIndex < pos + currentRun.Length)
            {
                if (currentRun.IsEndParagraph)
                {
                    return new TextEndOfParagraph(1);
                }

                var props =
                    new CustomTextRunProperties(currentRun.IsSuperscript);

                return new TextCharacters(
                    currentRun.Text,
                    textSourceCharacterIndex - pos,
                    currentRun.Length - (textSourceCharacterIndex - pos),
                    props);


            }
            pos += currentRun.Length;
        }

        // Return an end-of-paragraph if no more text source.
        return new TextEndOfParagraph(1);
    }

    public override TextSpan<CultureSpecificCharacterBufferRange> GetPrecedingText(int textSourceCharacterIndexLimit)
    {
        throw new Exception("The method or operation is not implemented.");
    }

    public override int GetTextEffectCharacterIndexFromTextSourceCharacterIndex(int textSourceCharacterIndex)
    {
        throw new Exception("The method or operation is not implemented.");
    }

    public int Length
    {
        get
        {
            int r = 0;
            foreach (var currentRun in Runs)
            {
                r += currentRun.Length;
            }
            return r;
        }
    }
}

所有这些就是剩下要做的就是初始化 CustomTextSource 并绘制文本:

     var textStore = new CustomTextSource();
     textStore.Runs.Add(new CustomTextSourceRun() { Text = "3" });
     textStore.Runs.Add(new CustomTextSourceRun() { Text = "rd", IsSuperscript = true });
     textStore.Runs.Add(new CustomTextSourceRun() { IsEndParagraph = true });
     textStore.Runs.Add(new CustomTextSourceRun() { Text = "4" });
     textStore.Runs.Add(new CustomTextSourceRun() { Text = "th", IsSuperscript = true });

     int textStorePosition = 0;
     System.Windows.Point linePosition = new System.Windows.Point(0, 0); 

     textDest = new DrawingGroup();
     DrawingContext dc = textDest.Open();

     TextFormatter formatter = TextFormatter.Create();

     while (textStorePosition < textStore.Length)
     {
        using (TextLine myTextLine = formatter.FormatLine(
            textStore,
            textStorePosition,
            96*6,
            new GenericTextParagraphProperties(FlowDirection.LeftToRight,
                TextAlignment.Left,true,false, new CustomTextRunProperties(false), TextWrapping.Wrap,
                30,0), null))
        {
            myTextLine.Draw(dc, linePosition, InvertAxes.None);
            textStorePosition += myTextLine.Length;
            linePosition.Y += myTextLine.Height;
        }
     }

     dc.Close();

就是这样 - 我们在绘图上下文中有上标文本。

FormattedText can't do subscript/superscript - but TextFormatter can.

TextFormatter is a low level API, you need to write a lot of code to use it - but most of the code is just subclassing all the classes used to pass formatting parameters int TextFormatter.

How to use TextFormatter

TextFormatter takes a TextSource object and produces multiple TextLine objects (one for each line), the TextLine.Draw method can then be used to draw the line to a drawing context.

The TextSource class is abstract, you have to subclass it and override the GetTextRun method that simply returns a TextRun object that's in the character position provided.

TextRun is also abstract - but it does have subclasses you can use - the interesting class is TextCharacters that contains a string and formatting information.

The formatting information is in a TextRunProperties object, unfortunately, this is another abstract class you have to subclass.

TextRunProperties has a TypographyProperties property of type TextRunTypographyProperties.

TextRunTypographyProperties is yet another abstract class you need to subclass.

And finally TextRunTypographyProperties has the Variants property you can use like the TextBlock example.

Code Example

Here is the minimal code I could write to draw superscript text:

First, Our TextRunProperties and TextRunTypographyProperties that can return superscript font variant:

class CustomTextRunProperties : TextRunProperties
{
    private bool _superscript;
    public CustomTextRunProperties(bool superscript)
    {
        _superscript = superscript;
    }
    public override System.Windows.Media.Brush BackgroundBrush
    {
        get { return null; }
    }

    public override CultureInfo CultureInfo
    {
        get { return CultureInfo.CurrentCulture; }
    }

    public override double FontHintingEmSize
    {
        get { return 22; }
    }

    public override double FontRenderingEmSize
    {
        get { return 22; }
    }

    public override Brush ForegroundBrush
    {
        get { return Brushes.Black; }
    }

    public override System.Windows.TextDecorationCollection TextDecorations
    {
        get { return new System.Windows.TextDecorationCollection(); }
    }

    public override System.Windows.Media.TextEffectCollection TextEffects
    {
        get { return new TextEffectCollection(); }
    }

    public override System.Windows.Media.Typeface Typeface
    {
        get { return new Typeface("Calibri"); }
    }

    public override TextRunTypographyProperties TypographyProperties
    {
        get
        {
            return new CustomTextRunTypographyProperties(_superscript);
        }
    }

}

class CustomTextRunTypographyProperties : TextRunTypographyProperties
{
    private bool _superscript;

    public CustomTextRunTypographyProperties(bool superscript)
    {
        _superscript = superscript;
    }

    public override int AnnotationAlternates
    {
        get { return 0; }
    }

    public override bool CapitalSpacing
    {
        get { return false; }
    }

    public override System.Windows.FontCapitals Capitals
    {
        get { return FontCapitals.Normal; }
    }

    public override bool CaseSensitiveForms
    {
        get { return false; }
    }

    public override bool ContextualAlternates
    {
        get { return false; }
    }

    public override bool ContextualLigatures
    {
        get { return false; }
    }

    public override int ContextualSwashes
    {
        get { return 0; }
    }

    public override bool DiscretionaryLigatures
    {
        get { return false; }
    }

    public override bool EastAsianExpertForms
    {
        get { return false; }
    }

    public override System.Windows.FontEastAsianLanguage EastAsianLanguage
    {
        get { return FontEastAsianLanguage.Normal; }
    }

    public override System.Windows.FontEastAsianWidths EastAsianWidths
    {
        get { return FontEastAsianWidths.Normal; }
    }

    public override System.Windows.FontFraction Fraction
    {
        get { return FontFraction.Normal; }
    }

    public override bool HistoricalForms
    {
        get { return false; }
    }

    public override bool HistoricalLigatures
    {
        get { return false; }
    }

    public override bool Kerning
    {
        get { return true; }
    }

    public override bool MathematicalGreek
    {
        get { return false; }
    }

    public override System.Windows.FontNumeralAlignment NumeralAlignment
    {
        get { return FontNumeralAlignment.Normal; }
    }

    public override System.Windows.FontNumeralStyle NumeralStyle
    {
        get { return FontNumeralStyle.Normal; }
    }

    public override bool SlashedZero
    {
        get { return false; }
    }

    public override bool StandardLigatures
    {
        get { return false; }
    }

    public override int StandardSwashes
    {
        get { return 0; }
    }

    public override int StylisticAlternates
    {
        get { return 0; }
    }

    public override bool StylisticSet1
    {
        get { return false; }
    }

    public override bool StylisticSet10
    {
        get { return false; }
    }

    public override bool StylisticSet11
    {
        get { return false; }
    }

    public override bool StylisticSet12
    {
        get { return false; }
    }

    public override bool StylisticSet13
    {
        get { return false; }
    }

    public override bool StylisticSet14
    {
        get { return false; }
    }

    public override bool StylisticSet15
    {
        get { return false; }
    }

    public override bool StylisticSet16
    {
        get { return false; }
    }

    public override bool StylisticSet17
    {
        get { return false; }
    }

    public override bool StylisticSet18
    {
        get { return false; }
    }

    public override bool StylisticSet19
    {
        get { return false; }
    }

    public override bool StylisticSet2
    {
        get { return false; }
    }

    public override bool StylisticSet20
    {
        get { return false; }
    }

    public override bool StylisticSet3
    {
        get { return false; }
    }

    public override bool StylisticSet4
    {
        get { return false; }
    }

    public override bool StylisticSet5
    {
        get { return false; }
    }

    public override bool StylisticSet6
    {
        get { return false; }
    }

    public override bool StylisticSet7
    {
        get { return false; }
    }

    public override bool StylisticSet8
    {
        get { return false; }
    }

    public override bool StylisticSet9
    {
        get { return false; }
    }

    public override FontVariants Variants
    {
        get { return _superscript ? FontVariants.Superscript: FontVariants.Normal; }
    }
}

And a similar class for paragraph formatting (takes from MSDN TextFormatter sample):

class GenericTextParagraphProperties : TextParagraphProperties
{
    public GenericTextParagraphProperties(
       FlowDirection flowDirection,
       TextAlignment textAlignment,
       bool firstLineInParagraph,
       bool alwaysCollapsible,
       TextRunProperties defaultTextRunProperties,
       TextWrapping textWrap,
       double lineHeight,
       double indent)
    {
        _flowDirection = flowDirection;
        _textAlignment = textAlignment;
        _firstLineInParagraph = firstLineInParagraph;
        _alwaysCollapsible = alwaysCollapsible;
        _defaultTextRunProperties = defaultTextRunProperties;
        _textWrap = textWrap;
        _lineHeight = lineHeight;
        _indent = indent;
    }

    public override FlowDirection FlowDirection
    {
        get { return _flowDirection; }
    }

    public override TextAlignment TextAlignment
    {
        get { return _textAlignment; }
    }

    public override bool FirstLineInParagraph
    {
        get { return _firstLineInParagraph; }
    }

    public override bool AlwaysCollapsible
    {
        get { return _alwaysCollapsible; }
    }

    public override TextRunProperties DefaultTextRunProperties
    {
        get { return _defaultTextRunProperties; }
    }

    public override TextWrapping TextWrapping
    {
        get { return _textWrap; }
    }

    public override double LineHeight
    {
        get { return _lineHeight; }
    }

    public override double Indent
    {
        get { return _indent; }
    }

    public override TextMarkerProperties TextMarkerProperties
    {
        get { return null; }
    }

    public override double ParagraphIndent
    {
        get { return _paragraphIndent; }
    }

    private FlowDirection _flowDirection;
    private TextAlignment _textAlignment;
    private bool _firstLineInParagraph;
    private bool _alwaysCollapsible;
    private TextRunProperties _defaultTextRunProperties;
    private TextWrapping _textWrap;
    private double _indent;
    private double _paragraphIndent;
    private double _lineHeight;
}

Now TextSource implementation:

public class CustomTextSourceRun
{
    public string Text;
    public bool IsSuperscript;
    public bool IsEndParagraph;
    public int Length { get { return IsEndParagraph ? 1 : Text.Length; } }
}


class CustomTextSource : TextSource
{
    public List<CustomTextSourceRun> Runs = new List<CustomTextSourceRun>();

    public override TextRun GetTextRun(int textSourceCharacterIndex)
    {
        int pos = 0;
        foreach (var currentRun in Runs)
        {
            if (textSourceCharacterIndex < pos + currentRun.Length)
            {
                if (currentRun.IsEndParagraph)
                {
                    return new TextEndOfParagraph(1);
                }

                var props =
                    new CustomTextRunProperties(currentRun.IsSuperscript);

                return new TextCharacters(
                    currentRun.Text,
                    textSourceCharacterIndex - pos,
                    currentRun.Length - (textSourceCharacterIndex - pos),
                    props);


            }
            pos += currentRun.Length;
        }

        // Return an end-of-paragraph if no more text source.
        return new TextEndOfParagraph(1);
    }

    public override TextSpan<CultureSpecificCharacterBufferRange> GetPrecedingText(int textSourceCharacterIndexLimit)
    {
        throw new Exception("The method or operation is not implemented.");
    }

    public override int GetTextEffectCharacterIndexFromTextSourceCharacterIndex(int textSourceCharacterIndex)
    {
        throw new Exception("The method or operation is not implemented.");
    }

    public int Length
    {
        get
        {
            int r = 0;
            foreach (var currentRun in Runs)
            {
                r += currentRun.Length;
            }
            return r;
        }
    }
}

And all that's left to do is initialize out CustomTextSource and draw the text:

     var textStore = new CustomTextSource();
     textStore.Runs.Add(new CustomTextSourceRun() { Text = "3" });
     textStore.Runs.Add(new CustomTextSourceRun() { Text = "rd", IsSuperscript = true });
     textStore.Runs.Add(new CustomTextSourceRun() { IsEndParagraph = true });
     textStore.Runs.Add(new CustomTextSourceRun() { Text = "4" });
     textStore.Runs.Add(new CustomTextSourceRun() { Text = "th", IsSuperscript = true });

     int textStorePosition = 0;
     System.Windows.Point linePosition = new System.Windows.Point(0, 0); 

     textDest = new DrawingGroup();
     DrawingContext dc = textDest.Open();

     TextFormatter formatter = TextFormatter.Create();

     while (textStorePosition < textStore.Length)
     {
        using (TextLine myTextLine = formatter.FormatLine(
            textStore,
            textStorePosition,
            96*6,
            new GenericTextParagraphProperties(FlowDirection.LeftToRight,
                TextAlignment.Left,true,false, new CustomTextRunProperties(false), TextWrapping.Wrap,
                30,0), null))
        {
            myTextLine.Draw(dc, linePosition, InvertAxes.None);
            textStorePosition += myTextLine.Length;
            linePosition.Y += myTextLine.Height;
        }
     }

     dc.Close();

And that's it - we have superscript text in a drawing context.

我不会写诗 2024-09-06 15:07:04

根本没有办法使用 FormattedText,请参阅此处的完整参考:

http://msdn.microsoft.com /en-us/library/system.windows.media.formattedtext_members.aspx

您可以使用它 TextBlock,正如您已经发现的:

在wpf中设置格式化文本的上标和下标


或者您可以简单地将 FormattedText 变小 (SetFontSize) 并手动将其放置在上方/下方。

如果您可以提供更多有关您使用 FormattedText 的情况、或者您试图解决的问题、或者为什么不能使用 TextBlock 的更多背景信息,请发布对此答案的回复,我们将很乐意提供更具体的示例帮助。

希望有帮助!

There simply isn't a way with FormattedText, see the complete reference here:

http://msdn.microsoft.com/en-us/library/system.windows.media.formattedtext_members.aspx

You can do with it TextBlock, as you have already discovered:

Set superscript and subscript in formatted text in wpf

Or you could simply make the FormattedText smaller (SetFontSize) and position it above/below manually.

If you could give some more context as to the situation you are using the FormattedText, or the problem you are trying to solve, or why you cannot use a TextBlock, please post a reply to this answer and we will be happy to help with more specific examples.

Hope that helps!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文