Render text easily in a WPF program using C#

[render text]

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,
        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 and see the previous post for more details.

Download Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in drawing, extension methods, geometry, graphics, wpf, XAML and tagged , , , , , , , , , , , , , , , , , . Bookmark the permalink.

2 Responses to Render text easily in a WPF program using C#

  1. Easily render rotated text in a WPF program using C#

    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 …

  2. Pingback: Easily render rotated text in a WPF program using C# - C# HelperC# Helper

Comments are closed.