[C# Helper]
Index Books FAQ Contact About Rod
[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[Beginning Software Engineering]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Render outlined text in a WPF program using C#

[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 FormattedText("Outlined\nText", new CultureInfo("en-us"), FlowDirection.LeftToRight, typeface, fontsize, Brushes.Black); formatted_text.SetFontWeight(FontWeights.Bold); // 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.

© 2009-2022 Rocky Mountain Computer Consulting, Inc. All rights reserved.