方法 : コントロールの背景にテキストを描画する

更新 : 2007 年 11 月

テキスト文字列を FormattedText オブジェクトに変換し、そのオブジェクトをコントロールの DrawingContext に描画することにより、コントロールの背景にテキストを直接描画できます。この手法は、CanvasStackPanel などの Panel から派生したオブジェクトの背景への描画にも使用できます。

カスタム テキスト背景のコントロールの例
テキストを背景として表示するコントロール

使用例

コントロールの背景に描画するには、新しい DrawingBrush オブジェクトを作成して、変換したテキストをオブジェクトの DrawingContext に描画します。次に、新しい DrawingBrush をコントロールの Background プロパティに割り当てます。

FormattedText オブジェクトを作成し、Label オブジェクトと Button オブジェクトの背景に描画する方法を次のコード例に示します。

// 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;
    }
}
ms748244.alert_note(ja-jp,VS.90).gifメモ :

次のコード例を含むコード サンプル全体については、「コントロールの背景へのテキストの描画のサンプル」を参照してください。

参照

概念

書式設定されたテキストの描画

参照

FormattedText