Title: Render outlined text in a WPF program using C#
The example Render text in a WPF program using C# shows how to draw basic text. This example uses the following overridden OnRender method to draw outlined text.
protected override void OnRender(DrawingContext drawingContext)
// Clear the background.
Rect bg_rect = new Rect(0, 0, ActualWidth, ActualHeight);
drawingContext.DrawRectangle(Brushes.White, null, bg_rect);
// Create the FormattedText.
const double fontsize = 70;
FontFamily font_family = new FontFamily("Segoe");
Typeface typeface = new Typeface("Segoe");
FormattedText formatted_text =
new CultureInfo("en-us"), FlowDirection.LeftToRight,
typeface, fontsize, Brushes.Black);
// Center horizontally.
formatted_text.TextAlignment = TextAlignment.Center;
// Pick an origin to center the text.
Point origin = new Point(
grdMain.ActualWidth / 2,
(grdMain.ActualHeight - formatted_text.Height) / 2);
// Convert the text into geometry.
Geometry geometry = formatted_text.BuildGeometry(origin);
// Draw the geometry.
Pen pen = new Pen(Brushes.Red, 2);
drawingContext.DrawGeometry(Brushes.Yellow, pen, geometry);
The method starts by clearing the drawing area. It then creates a Typeface representing the Segoe (pronounced "see-go") font and uses it to make a FormattedText object. It uses that object's SetFontWeight method to make the text bold. Outlined text works best when the characters have relatively large internal spaces, so bold Gothic fonts such as Segoe work well.
The code sets the text's alignment and calculates the position where the text should be drawn. It then calls the FormattedText object's BuildGeometry method to convert the text into a sequence of drawing commands. It finishes by calling the DrawingContext object's DrawGeometry method to draw the geometry, filling it with a yellow brush and outlining it with a red pen.
Download the example to experiment with it and to see additional details.