Compartir a través de


Cómo: Crear texto con contorno

En la mayoría de los casos, al agregar ornamentación a las cadenas de texto en una aplicación de Windows Presentation Foundation (WPF), se utiliza el texto considerándolo una colección de caracteres discretos, o glifos. Por ejemplo, podría crear un pincel de degradado lineal y aplicarlo a la propiedad Foreground de un objeto TextBox. Al mostrar o modificar el cuadro de texto, el pincel de degradado lineal se aplica automáticamente al conjunto actual de caracteres de la cadena de texto.

Ejemplo de un pincel de degradado lineal aplicado a un cuadro de texto

Texto que se muestra con un pincel de degradado lineal

Sin embargo, también puede convertir el texto en objetos Geometry, lo que permite crear otros tipos de texto visualmente enriquecido. Por ejemplo, podría crear un objeto Geometry basado en el contorno de una cadena de texto.

Ejemplo de un pincel de degradado lineal aplicado a la geometría del contorno de texto

Esquema de texto que usa un pincel de degradado lineal

Cuando se convierte el texto en un objeto Geometry, deja de ser una colección de caracteres; no se pueden modificar los caracteres de la cadena de texto. Sin embargo, se puede cambiar la apariencia del texto convertido modificando sus propiedades de trazo y relleno. El trazo se refiere al contorno del texto convertido; el relleno se refiere al área situada dentro del contorno del texto convertido.

En los ejemplos siguientes se muestran varias maneras de crear efectos visuales modificando el trazo y el relleno del texto convertido.

Ejemplo de cómo establecer el trazo y el relleno en diferentes colores

Texto con colores diferentes para relleno y trazo

Ejemplo de un pincel de imagen aplicado al trazo

Texto con pincel de imagen aplicado a trazo

También es posible modificar el rectángulo de selección o resaltado del texto convertido. En el ejemplo siguiente se muestra una manera de crear efectos visuales modificando el trazo y el resaltado del texto convertido.

Ejemplo de un pincel de imagen aplicado al trazo y al resaltado

Texto con pincel de imagen aplicado a trazo

Ejemplo

La clave para convertir texto en un objeto Geometry es utilizar el objeto FormattedText. Una vez creado este objeto, puede utilizar los métodos BuildGeometry y BuildHighlightGeometry para convertir el texto en objetos Geometry. El primer método devuelve la geometría del texto con formato; el segundo método devuelve la geometría del rectángulo de selección del texto con formato. En el ejemplo de código siguiente se muestra cómo crear un objeto FormattedText y recuperar las geometrías del texto con formato y su rectángulo de selección.

        ''' <summary>
        ''' Create the outline geometry based on the formatted text.
        ''' </summary>
        Public Sub CreateText()
            Dim fontStyle As FontStyle = FontStyles.Normal
            Dim fontWeight As FontWeight = FontWeights.Medium

            If Bold = True Then
                fontWeight = FontWeights.Bold
            End If
            If Italic = True Then
                fontStyle = FontStyles.Italic
            End If

            ' Create the formatted text based on the properties set.
            Dim formattedText As New FormattedText(Text, CultureInfo.GetCultureInfo("en-us"), FlowDirection.LeftToRight, New Typeface(Font, fontStyle, fontWeight, FontStretches.Normal), FontSize, Brushes.Black) ' This brush does not matter since we use the geometry of the text.

            ' Build the geometry object that represents the text.
            _textGeometry = formattedText.BuildGeometry(New Point(0, 0))

            ' Build the geometry object that represents the text hightlight.
            If Highlight = True Then
                _textHighLightGeometry = formattedText.BuildHighlightGeometry(New Point(0, 0))
            End If
        End Sub
/// <summary>
/// Create the outline geometry based on the formatted text.
/// </summary>
public void CreateText()
{
    System.Windows.FontStyle fontStyle = FontStyles.Normal;
    FontWeight fontWeight = FontWeights.Medium;

    if (Bold == true) fontWeight = FontWeights.Bold;
    if (Italic == true) fontStyle = FontStyles.Italic;

    // Create the formatted text based on the properties set.
    FormattedText formattedText = new FormattedText(
        Text,
        CultureInfo.GetCultureInfo("en-us"),
        FlowDirection.LeftToRight,
        new Typeface(
            Font,
            fontStyle,
            fontWeight,
            FontStretches.Normal),
        FontSize,
        System.Windows.Media.Brushes.Black // This brush does not matter since we use the geometry of the text. 
        );

    // Build the geometry object that represents the text.
    _textGeometry = formattedText.BuildGeometry(new System.Windows.Point(0, 0));

    // Build the geometry object that represents the text hightlight.
    if (Highlight == true)
    {
        _textHighLightGeometry = formattedText.BuildHighlightGeometry(new System.Windows.Point(0, 0));
    }
}

Para mostrar los objetos Geometry recuperados, deberá tener acceso al DrawingContext del objeto que muestra el texto convertido. En estos ejemplos de código, esto se hace creando un objeto de control personalizado derivado de una clase que admite la representación definida por el usuario.

Para mostrar objetos Geometry en el control personalizado, invalide el método OnRender. El método invalidado deberá utilizar el método DrawGeometry para dibujar los objetos Geometry.

        ''' <summary>
        ''' OnRender override draws the geometry of the text and optional highlight.
        ''' </summary>
        ''' <param name="drawingContext">Drawing context of the OutlineText control.</param>
        Protected Overrides Sub OnRender(ByVal drawingContext As DrawingContext)
            ' Draw the outline based on the properties that are set.
            drawingContext.DrawGeometry(Fill, New Pen(Stroke, StrokeThickness), _textGeometry)

            ' Draw the text highlight based on the properties that are set.
            If Highlight = True Then
                drawingContext.DrawGeometry(Nothing, New Pen(Stroke, StrokeThickness), _textHighLightGeometry)
            End If
        End Sub
/// <summary>
/// OnRender override draws the geometry of the text and optional highlight.
/// </summary>
/// <param name="drawingContext">Drawing context of the OutlineText control.</param>
protected override void OnRender(DrawingContext drawingContext)
{
    // Draw the outline based on the properties that are set.
    drawingContext.DrawGeometry(Fill, new System.Windows.Media.Pen(Stroke, StrokeThickness), _textGeometry);

    // Draw the text highlight based on the properties that are set.
    if (Highlight == true)
    {
        drawingContext.DrawGeometry(null, new System.Windows.Media.Pen(Stroke, StrokeThickness), _textHighLightGeometry);
    }
}

Vea también

Conceptos

Dibujar texto con formato