Title: Render text in a WPF program using C#
Normally to display text in WPF you use some sort of object such as a Label or TextBlock, but you can draw text yourself if necessary. To make this easier, at design time I set the window's Background property to Transparent (otherwise the window draws the background on top of any text you draw). I also named the main control grdMain to make it easy to tell how big the window's client area is.
To draw the text, override the window's OnRender method and use its drawingContext parameter to do the drawing. This program uses the following OnRender method.
protected override void OnRender(DrawingContext drawingContext)
// Clear the background and draw an ellipse.
// Make the FormattedText object.
Typeface typeface = new Typeface("Times New Roman");
double em_size = 40;
FormattedText formatted_text = new FormattedText(
typeface, em_size, Brushes.Red);
// Center the text horizontally.
formatted_text.TextAlignment = TextAlignment.Center;
// Find the center of the client area.
double xmid = grdMain.ActualWidth / 2;
double ymid = grdMain.ActualHeight / 2;
Point center =
new Point(xmid, ymid - formatted_text.Height / 2);
// Draw the text.
// Draw an ellipse at the text's drawing point.
drawingContext.DrawEllipse(Brushes.Green, null, center, 3, 3);
This method starts by calling the DrawEllipse method to draw an ellipse that fills the window. See the example Render an ellipse in a WPF program using C# for information about how that method works.
Next the code creates a Typeface object to represent the font to use, in this case Times New Roman. It then uses the Typeface to create a FormattedText object. That object represents a particular piece of text drawn with a specific brush. The FormattedText constructor takes as a parameter the culture that should be used to draw the text. This example simply uses the program's current user interface culture.
In addition to specifying the brush to use, the FormattedText object provides properties and methods to let you control the text formatting in other ways. This example sets the object's TextAlignment property to center the text horizontally.
Unlike the StringFormat class in GDI+, the TextAlignment property doesn't give you any control over the text's vertical alignment. To align text vertically, you need to measure the text and calculate the proper Y coordinate.
This example uses the size of the grdMain control to find the center of the window's client area. It then subtracts half of the formatted text's height from the Y coordinate to center the text vertically.
The code then calls the DrawingContext object's DrawText method to draw the text. Finally the method draws a small green ellipse to show the text's reference point, the point passed into the DrawText method.
Download the example to experiment with it and to see additional details.