如何:将文本绘制到控件的背景上

更新:2007 年 11 月

可以将文本直接绘制到控件的背景上,方法是将文本字符串转换为 FormattedText 对象,然后将该对象绘制到控件的 DrawingContext 中。还可以使用这种方法来绘制到派生自 Panel 的对象(如 CanvasStackPanel)的背景上。

具有自定义文本背景的控件的示例

将文本作为背景显示的控件

示例

若要绘制到某个控件的背景上,请创建一个新的 DrawingBrush 对象,并将转换后的文本绘制到该对象的 DrawingContext 中。然后,将新的 DrawingBrush 分配给该控件的背景属性。

下面的代码示例演示如何创建 FormattedText 对象,并将其绘制到 LabelButton 对象的背景上。

// 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