Title: Render text easily in a WPF program using C#
The example Render text in a WPF program using C# explains how to draw text in WPF code. This example uses the following extension method to make drawing text easier.
// Draw text at the indicated location.
public static void DrawString(this DrawingContext drawing_context,
string text, string font_name, double em_size, Brush brush,
Point origin, VertAlignment valign, TextAlignment halign)
{
Typeface typeface = new Typeface(font_name);
FormattedText formatted_text = new FormattedText(
text, CultureInfo.CurrentUICulture,
FlowDirection.LeftToRight,
typeface, em_size, brush);
formatted_text.TextAlignment = halign;
if (valign == VertAlignment.Middle)
origin.Y -= formatted_text.Height / 2;
else if (valign == VertAlignment.Bottom)
origin.Y -= formatted_text.Height;
drawing_context.DrawText(formatted_text, origin);
}
This method takes parameters that describe the text to draw. It uses them to create the Typeface and FormattedText objects it needs. It sets the FormattedText object's TextAlignment property to align the text horizontally as desired.
If the valign parameter indicates the text should be centered vertically, the code subtracts half of the text's height from the drawing origin's Y coordinate. If valign indicates the text should be aligned at the bottom, the code subtracts the text's full height from the drawing origin's Y coordinate to give it the correct vertical position.
The method finishes by calling the DrawingContext object's DrawText method to draw the text.
The following code shows how the main program uses the extension method to draw the text in the upper right.
drawingContext.DrawString("TOP\nRIGHT", font_name, em_size,
Brushes.Black, point, VertAlignment.Top, TextAlignment.Right);
Download the example to experiment with it and to see additional details.
|