Edit

Share via


Drawing Formatted Text

This topic provides an overview of the features of the FormattedText object. This object provides low-level control for drawing text in Windows Presentation Foundation (WPF) applications.

Technology Overview

The FormattedText object allows you to draw multi-line text, in which each character in the text can be individually formatted. The following example shows text that has several formats applied to it.

Text displayed using FormattedText object

Note

For those developers migrating from the Win32 API, the table in the Win32 Migration section lists the Win32 DrawText flags and the approximate equivalent in Windows Presentation Foundation (WPF).

Reasons for Using Formatted Text

WPF includes multiple controls for drawing text to the screen. Each control is targeted to a different scenario and has its own list of features and limitations. In general, the TextBlock element should be used when limited text support is required, such as a brief sentence in a user interface (UI). Label can be used when minimal text support is required. For more information, see Documents in WPF.

The FormattedText object provides greater text formatting features than Windows Presentation Foundation (WPF) text controls, and can be useful in cases where you want to use text as a decorative element. For more information, see the following section Converting Formatted Text to a Geometry.

In addition, the FormattedText object is useful for creating text-oriented DrawingVisual-derived objects. DrawingVisual is a lightweight drawing class that is used to render shapes, images, or text. For more information, see Hit Test Using DrawingVisuals Sample.

Using the FormattedText Object

To create formatted text, call the FormattedText constructor to create a FormattedText object. Once you have created the initial formatted text string, you can apply a range of formatting styles.

Use the MaxTextWidth property to constrain the text to a specific width. The text will automatically wrap to avoid exceeding the specified width. Use the MaxTextHeight property to constrain the text to a specific height. The text will display an ellipsis, "…" for the text that exceeds the specified height.

Text displayed with wordwrap and ellipsis.

You can apply multiple formatting styles to one or more characters. For example, you could call both the SetFontSize and SetForegroundBrush methods to change the formatting of the first five characters in the text.

The following code example creates a FormattedText object and then applies several formatting styles to the text.

protected override void OnRender(DrawingContext drawingContext)
{
    string testString = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor";

    // Create the initial formatted text string.
    FormattedText formattedText = new FormattedText(
        testString,
        CultureInfo.GetCultureInfo("en-us"),
        FlowDirection.LeftToRight,
        new Typeface("Verdana"),
        32,
        Brushes.Black);

    // Set a maximum width and height. If the text overflows these values, an ellipsis "..." appears.
    formattedText.MaxTextWidth = 300;
    formattedText.MaxTextHeight = 240;

    // Use a larger font size beginning at the first (zero-based) character and continuing for 5 characters.
    // The font size is calculated in terms of points -- not as device-independent pixels.
    formattedText.SetFontSize(36 * (96.0 / 72.0), 0, 5);

    // Use a Bold font weight beginning at the 6th character and continuing for 11 characters.
    formattedText.SetFontWeight(FontWeights.Bold, 6, 11);

    // Use a linear gradient brush beginning at the 6th character and continuing for 11 characters.
    formattedText.SetForegroundBrush(
                            new LinearGradientBrush(
                            Colors.Orange,
                            Colors.Teal,
                            90.0),
                            6, 11);

    // Use an Italic font style beginning at the 28th character and continuing for 28 characters.
    formattedText.SetFontStyle(FontStyles.Italic, 28, 28);

    // Draw the formatted text string to the DrawingContext of the control.
    drawingContext.DrawText(formattedText, new Point(10, 0));
}
Protected Overrides Sub OnRender(ByVal drawingContext As DrawingContext)
    Dim testString As String = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor"

    ' Create the initial formatted text string.
    Dim formattedText As New FormattedText(testString, CultureInfo.GetCultureInfo("en-us"), FlowDirection.LeftToRight, New Typeface("Verdana"), 32, Brushes.Black)

    ' Set a maximum width and height. If the text overflows these values, an ellipsis "..." appears.
    formattedText.MaxTextWidth = 300
    formattedText.MaxTextHeight = 240

    ' Use a larger font size beginning at the first (zero-based) character and continuing for 5 characters.
    ' The font size is calculated in terms of points -- not as device-independent pixels.
    formattedText.SetFontSize(36 * (96.0 / 72.0), 0, 5)

    ' Use a Bold font weight beginning at the 6th character and continuing for 11 characters.
    formattedText.SetFontWeight(FontWeights.Bold, 6, 11)

    ' Use a linear gradient brush beginning at the 6th character and continuing for 11 characters.
    formattedText.SetForegroundBrush(New LinearGradientBrush(Colors.Orange, Colors.Teal, 90.0), 6, 11)

    ' Use an Italic font style beginning at the 28th character and continuing for 28 characters.
    formattedText.SetFontStyle(FontStyles.Italic, 28, 28)

    ' Draw the formatted text string to the DrawingContext of the control.
    drawingContext.DrawText(formattedText, New Point(10, 0))
End Sub

Font Size Unit of Measure

As with other text objects in Windows Presentation Foundation (WPF) applications, the FormattedText object uses device-independent pixels as the unit of measure. However, most Win32 applications use points as the unit of measure. If you want to use display text in units of points in Windows Presentation Foundation (WPF) applications, you need to convert device-independent units (1/96th inch per unit) to points. The following code example shows how to perform this conversion.

// The font size is calculated in terms of points -- not as device-independent pixels.
formattedText.SetFontSize(36 * (96.0 / 72.0), 0, 5);
' The font size is calculated in terms of points -- not as device-independent pixels.
formattedText.SetFontSize(36 * (96.0 / 72.0), 0, 5)

Converting Formatted Text to a Geometry

You can convert formatted text into Geometry objects, allowing you to create other types of visually interesting text. For example, you could create a Geometry object based on the outline of a text string.

Text outline using a linear gradient brush

The following examples illustrate several ways of creating interesting visual effects by modifying the stroke, fill, and highlight of converted text.

Text with different colors for fill and stroke

Text with image brush applied to stroke

Text with image brush applied to stroke and highlight

When text is converted to a Geometry object, it is no longer a collection of characters—you cannot modify the characters in the text string. However, you can affect the appearance of the converted text by modifying its stroke and fill properties. The stroke refers to the outline of the converted text; the fill refers to the area inside the outline of the converted text. For more information, see Create Outlined Text.

You can also convert formatted text to a PathGeometry object, and use the object for highlighting the text. For example, you could apply an animation to the PathGeometry object so that the animation follows the outline of the formatted text.

The following example shows formatted text that has been converted to a PathGeometry object. An animated ellipse follows the path of the strokes of the rendered text.

Sphere following the path geometry of text
Sphere following the path geometry of text

For more information, see How to: Create a PathGeometry Animation for Text.

You can create other interesting uses for formatted text once it has been converted to a PathGeometry object. For example, you can clip video to display inside it.

Video displaying in the path geometry of text

Win32 Migration

The features of FormattedText for drawing text are similar to the features of the Win32 DrawText function. For those developers migrating from the Win32 API, the following table lists the Win32 DrawText flags and the approximate equivalent in Windows Presentation Foundation (WPF).

DrawText flag WPF equivalent Notes
DT_BOTTOM Height Use the Height property to compute an appropriate Win32 DrawText 'y' position.
DT_CALCRECT Height, Width Use the Height and Width properties to calculate the output rectangle.
DT_CENTER TextAlignment Use the TextAlignment property with the value set to Center.
DT_EDITCONTROL None Not required. Space width and last line rendering are the same as in the framework edit control.
DT_END_ELLIPSIS Trimming Use the Trimming property with the value CharacterEllipsis.

Use WordEllipsis to get Win32 DT_END_ELLIPSIS with DT_WORD_ELIPSIS end ellipsis—in this case, character ellipsis only occurs on words that do not fit on a single line.
DT_EXPAND_TABS None Not required. Tabs are automatically expanded to stops every 4 ems, which is approximately the width of 8 language-independent characters.
DT_EXTERNALLEADING None Not required. External leading is always included in line spacing. Use the LineHeight property to create user-defined line spacing.
DT_HIDEPREFIX None Not supported. Remove the '&' from the string before constructing the FormattedText object.
DT_LEFT TextAlignment This is the default text alignment. Use the TextAlignment property with the value set to Left. (WPF only)
DT_MODIFYSTRING None Not supported.
DT_NOCLIP VisualClip Clipping does not happen automatically. If you want to clip text, use the VisualClip property.
DT_NOFULLWIDTHCHARBREAK None Not supported.
DT_NOPREFIX None Not required. The '&' character in strings is always treated as a normal character.
DT_PATHELLIPSIS None Use the Trimming property with the value WordEllipsis.
DT_PREFIX None Not supported. If you want to use underscores for text, such as an accelerator key or link, use the SetTextDecorations method.
DT_PREFIXONLY None Not supported.
DT_RIGHT TextAlignment Use the TextAlignment property with the value set to Right. (WPF only)
DT_RTLREADING FlowDirection Set the FlowDirection property to RightToLeft.
DT_SINGLELINE None Not required. FormattedText objects behave as a single line control, unless either the MaxTextWidth property is set or the text contains a carriage return/line feed (CR/LF).
DT_TABSTOP None No support for user-defined tab stop positions.
DT_TOP Height Not required. Top justification is the default. Other vertical positioning values can be defined by using the Height property to compute an appropriate Win32 DrawText 'y' position.
DT_VCENTER Height Use the Height property to compute an appropriate Win32 DrawText 'y' position.
DT_WORDBREAK None Not required. Word breaking happens automatically with FormattedText objects. You cannot disable it.
DT_WORD_ELLIPSIS Trimming Use the Trimming property with the value WordEllipsis.

See also