Como: Criar texto destacado

Na maioria dos casos, quando você está adicionando ornamentação a cadeias de caracteres de texto em seu aplicativo Windows Presentation Foundation (WPF), você está usando texto em termos de uma coleção de caracteres discretos ou glifos. Por exemplo, você pode criar um pincel de gradiente linear e aplicá-lo à Foreground propriedade de um TextBox objeto. Ao exibir ou editar a caixa de texto, o pincel de gradiente linear é aplicado automaticamente ao conjunto de caracteres atual na cadeia de texto.

Text displayed with a linear gradient brush

No entanto, você também pode converter texto em Geometry objetos, permitindo que você crie outros tipos de texto visualmente rico. Por exemplo, você pode criar um Geometry objeto com base na estrutura de tópicos de uma cadeia de caracteres de texto.

Text outline using a linear gradient brush

Quando o texto é convertido em um Geometry objeto, ele não é mais uma coleção de caracteres — você não pode modificar os caracteres na cadeia de caracteres de texto. No entanto, é possível afetar a aparência do texto convertido modificando suas propriedades de traço e preenchimento. O traço refere-se ao contorno do texto convertido; o preenchimento refere-se à área dentro do contorno do texto convertido.

Os exemplos a seguir ilustram várias maneiras de criar efeitos visuais modificando o traço e o preenchimento do texto convertido.

Text with different colors for fill and stroke

Text with image brush applied to stroke

Também é possível modificar o retângulo da caixa delimitadora ou realce, do texto convertido. O exemplo a seguir ilustra uma maneira de criar efeitos visuais modificando o traçado e o realce do texto convertido.

Text with image brush applied to stroke and highlight

Exemplo

A chave para converter texto em um Geometry objeto é usar o FormattedText objeto. Depois de criar esse objeto, você pode usar os BuildGeometry métodos e BuildHighlightGeometry para converter o texto em Geometry objetos. O primeiro método retorna a geometria do texto formatado; o segundo método retorna a geometria da caixa delimitadora do texto formatado. O exemplo de código a seguir mostra como criar um FormattedText objeto e recuperar as geometrias do texto formatado e sua caixa delimitadora.

/// <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 highlight.
    if (Highlight == true)
    {
        _textHighLightGeometry = formattedText.BuildHighlightGeometry(new System.Windows.Point(0, 0));
    }
}
''' <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 highlight.
    If Highlight = True Then
        _textHighLightGeometry = formattedText.BuildHighlightGeometry(New Point(0, 0))
    End If
End Sub

Para exibir os objetos recuperados Geometry , você precisa acessar o DrawingContext do objeto que está exibindo o texto convertido. Nesses exemplos de código, esse acesso é obtido criando um objeto de controle personalizado derivado de uma classe que oferece suporte à renderização definida pelo usuário.

Para exibir Geometry objetos no controle personalizado, forneça uma substituição para o OnRender método. Seu método substituído deve usar o DrawGeometry método para desenhar os Geometry objetos.

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

Para obter a origem do objeto de controle de usuário personalizado de exemplo, consulte OutlineTextControl.cs para C# e OutlineTextControl.vb para Visual Basic.

Confira também