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!
Share
FormattedTextcan’t do subscript/superscript – butTextFormattercan.TextFormatteris 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 intTextFormatter.How to use TextFormatter
TextFormattertakes aTextSourceobject and produces multipleTextLineobjects (one for each line), theTextLine.Drawmethod can then be used to draw the line to a drawing context.The
TextSourceclass is abstract, you have to subclass it and override theGetTextRunmethod that simply returns aTextRunobject that’s in the character position provided.TextRunis also abstract – but it does have subclasses you can use – the interesting class isTextCharactersthat contains a string and formatting information.The formatting information is in a
TextRunPropertiesobject, unfortunately, this is another abstract class you have to subclass.TextRunPropertieshas aTypographyPropertiesproperty of typeTextRunTypographyProperties.TextRunTypographyPropertiesis yet another abstract class you need to subclass.And finally
TextRunTypographyPropertieshas theVariantsproperty 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:
And a similar class for paragraph formatting (takes from MSDN TextFormatter sample):
Now TextSource implementation:
And all that’s left to do is initialize out CustomTextSource and draw the text:
And that’s it – we have superscript text in a drawing context.