How to: Draw Text to a Visual

The following example shows how to draw text to a DrawingVisual using a DrawingContext object. A drawing context is returned by calling the RenderOpen method of a DrawingVisual object. You can draw graphics and text into a drawing context.

To draw text into the drawing context, use the DrawText method of a DrawingContext object. When you are finished drawing content into the drawing context, call the Close method to close the drawing context and persist the content.

Example

// Create a DrawingVisual that contains text.
private DrawingVisual CreateDrawingVisualText()
{
    // Create an instance of a DrawingVisual.
    DrawingVisual drawingVisual = new DrawingVisual();

    // Retrieve the DrawingContext from the DrawingVisual.
    DrawingContext drawingContext = drawingVisual.RenderOpen();

    // Draw a formatted text string into the DrawingContext.
    drawingContext.DrawText(
       new FormattedText("Click Me!",
          CultureInfo.GetCultureInfo("en-us"),
          FlowDirection.LeftToRight,
          new Typeface("Verdana"),
          36, System.Windows.Media.Brushes.Black),
          new System.Windows.Point(200, 116));

    // Close the DrawingContext to persist changes to the DrawingVisual.
    drawingContext.Close();

    return drawingVisual;
}
' Create a DrawingVisual that contains text.
Private Function CreateDrawingVisualText() As DrawingVisual
	' Create an instance of a DrawingVisual.
	Dim drawingVisual As New DrawingVisual()

	' Retrieve the DrawingContext from the DrawingVisual.
	Dim drawingContext As DrawingContext = drawingVisual.RenderOpen()

	' Draw a formatted text string into the DrawingContext.
	drawingContext.DrawText(New FormattedText("Click Me!", CultureInfo.GetCultureInfo("en-us"), FlowDirection.LeftToRight, New Typeface("Verdana"), 36, Brushes.Black), New Point(200, 116))

	' Close the DrawingContext to persist changes to the DrawingVisual.
	drawingContext.Close()

	Return drawingVisual
End Function
Note

For the complete code sample from which the preceding code example was extracted, see Hit Test Using DrawingVisuals Sample.