BLOG.CSHARPHELPER.COM: Use an extension method to easily render text in a WPF program using C#
Use an extension method to easily render text 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'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's DrawText method to draw the text.
4/30/2014 7:54 AM
BLOG.CSHARPHELPER.COM wrote:
The example Use an extension method to easily render text in a WPF program using C# shows how to make an extension method that makes rendering text easy in WPF. This example makes a similar extension method for rendering rotated text. The title of this post includes the word "easily." By that I mean it's easy to use the extension method, not that it's easy to write the method. This is a fairly confusing extension method, so I'm going to show the code in pieces. Most of the extension method's parameters are straightforward, but ...
Comments