Compartilhar 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.

Este tópico contém as seguintes seções.

  • Technology Overview
  • Using the FormattedText Object
  • Win32 Migration
  • Tópicos relacionados

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.

Displayed text using FormattedText method

Texto exibido com o objeto FormattedText

Observação

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. Em geral, o TextBlock elemento a ser usado quando suporte limitado de texto é necessária, como, por exemplo, uma breve frase em um user interface (UI). Labelpode ser usado quando o suporte a quantidade mínima de texto é necessária. For more information, see Documentos no WPF.

O FormattedText objeto fornece recursos de formatação de texto maiores que Windows Presentation Foundation (WPF) controles de texto e pode ser útil em casos onde você deseja usar o texto como um elemento decorativo. Para obter mais informações, consulte a seção a seguir Converter texto formatado em uma geometria.

Além disso, o FormattedText o objeto é útil para a criação orientada por texto DrawingVisual-derivado objetos. DrawingVisualé uma classe de desenho leve que é usada para processar as formas, imagens ou texto. Para obter mais informações, consulte Visitas teste usando o exemplo DrawingVisuals.

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.

Displayed text showing wordwrapping and ellipsis

Texto exibido com o objeto FormattedText

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 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
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));
}

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. Se você deseja usar o texto de exibição em unidades de pontos em Windows Presentation Foundation (WPF) aplicativos, você precisa converter device-independent units (1/96th inch per unit) pontos. 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

Contorno do texto usando um pincel de gradiente linear

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

Example of setting stroke and fill to different colors

Texto com cores diferentes de preenchimento e traço

Example of an image brush applied to the stroke

Texto com pincel de imagem aplicado ao traço

Example of an image brush applied to the stroke and highlight

Texto com pincel de imagem aplicado ao traço

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 Como: Desenhar a borda de um texto.

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

Esfera seguindo a geometria de caminho do texto

For more information, see Como: 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

Vídeo em exibição na geometria de caminho do texto

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

Não é suportado. 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

Não é suportado.

DT_NOCLIP

VisualClip

Clipping does not happen automatically. If you want to clip text, use the VisualClip property.

DT_NOFULLWIDTHCHARBREAK

None

Não é suportado.

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

Não é suportado. If you want to use underscores for text, such as an accelerator key or link, use the SetTextDecorations method.

DT_PREFIXONLY

None

Não é suportado.

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. FormattedTextobjetos se comportem como um controle de única linha, a menos que tanto o MaxTextWidth propriedade estiver definida ou o texto contém uma carro retorno/alimentação de linha (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.

Consulte também

Tarefas

Como: Desenhar a borda de um texto

Referência

FormattedText

Conceitos

Documentos no WPF

Tipologia no WPF

Como: Create a PathGeometry Animation for Text