Поделиться через


Практическое руководство. Рисование текста на фоне элемента управления

Можно нарисовать текст непосредственно на фоне элемента управления с помощью преобразования текстовой строки в объект FormattedText и затем отобразив его в объекте DrawingContext элемента управления. Можно также использовать этот метод для рисования на фоне объектов, производных от объекта Panel, например Canvas и StackPanel.

Пример элементов управления с пользовательским текстом на фоне

Элементы управления, отображающие текст в качестве фона

Пример

Чтобы рисовать на фоне элемента управления, создайте новый объект DrawingBrush и нарисуйте преобразованный текст в классе DrawingContext объекта. Затем назначьте новый объект DrawingBrush свойству фона элемента управления.

В следующем примере показано, как создать объект FormattedText и рисовать на фоне объектов Label и Button.

        ' Handle the WindowLoaded event for the window.
        Private Sub WindowLoaded(ByVal sender As Object, ByVal e As EventArgs)
            ' Update the background property of the label and button.
            myLabel.Background = New DrawingBrush(DrawMyText("My Custom Label"))
            myButton.Background = New DrawingBrush(DrawMyText("Display Text"))
        End Sub

        ' Convert the text string to a geometry and draw it to the control's DrawingContext.
        Private Function DrawMyText(ByVal textString As String) As Drawing
            ' Create a new DrawingGroup of the control.
            Dim drawingGroup As New DrawingGroup()

            ' Open the DrawingGroup in order to access the DrawingContext.
            Using drawingContext As DrawingContext = drawingGroup.Open()
                ' Create the formatted text based on the properties set.
                Dim formattedText As New FormattedText(textString, CultureInfo.GetCultureInfo("en-us"), FlowDirection.LeftToRight, New Typeface("Comic Sans MS Bold"), 48, Brushes.Black) ' This brush does not matter since we use the geometry of the text.

                ' Build the geometry object that represents the text.
                Dim textGeometry As Geometry = formattedText.BuildGeometry(New Point(20, 0))

                ' Draw a rounded rectangle under the text that is slightly larger than the text.
                drawingContext.DrawRoundedRectangle(Brushes.PapayaWhip, Nothing, New Rect(New Size(formattedText.Width + 50, formattedText.Height + 5)), 5.0, 5.0)

                ' Draw the outline based on the properties that are set.
                drawingContext.DrawGeometry(Brushes.Gold, New Pen(Brushes.Maroon, 1.5), textGeometry)

                ' Return the updated DrawingGroup content to be used by the control.
                Return drawingGroup
            End Using
        End Function
// Handle the WindowLoaded event for the window.
private void WindowLoaded(object sender, EventArgs e) 
{
    // Update the background property of the label and button.
    myLabel.Background = new DrawingBrush(DrawMyText("My Custom Label"));
    myButton.Background = new DrawingBrush(DrawMyText("Display Text"));
}

// Convert the text string to a geometry and draw it to the control's DrawingContext.
private Drawing DrawMyText(string textString)
{
    // Create a new DrawingGroup of the control.
    DrawingGroup drawingGroup = new DrawingGroup();

    // Open the DrawingGroup in order to access the DrawingContext.
    using (DrawingContext drawingContext = drawingGroup.Open())
    {
        // Create the formatted text based on the properties set.
        FormattedText formattedText = new FormattedText(
            textString,
            CultureInfo.GetCultureInfo("en-us"),
            FlowDirection.LeftToRight,
            new Typeface("Comic Sans MS Bold"),
            48,
            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.
        Geometry textGeometry = formattedText.BuildGeometry(new System.Windows.Point(20, 0));

        // Draw a rounded rectangle under the text that is slightly larger than the text.
        drawingContext.DrawRoundedRectangle(System.Windows.Media.Brushes.PapayaWhip, null, new Rect(new System.Windows.Size(formattedText.Width + 50, formattedText.Height + 5)), 5.0, 5.0);

        // Draw the outline based on the properties that are set.
        drawingContext.DrawGeometry(System.Windows.Media.Brushes.Gold, new System.Windows.Media.Pen(System.Windows.Media.Brushes.Maroon, 1.5), textGeometry);

        // Return the updated DrawingGroup content to be used by the control.
        return drawingGroup;
    }
}

См. также

Ссылки

FormattedText

Основные понятия

Рисование форматированного текста