Text Rendering

There are numerous classes presented by GDI+ and GDI for rendering text on Windows Forms. The GDI+ Graphics class has several DrawString methods that allow you to specify various features of text, such as location, bounding rectangle, font, and format. In addition, you can draw and measure text with GDI using the static DrawText and MeasureText methods offered by the TextRenderer class. The GDI methods also allow you to specify location, font, and format.

In the case of RightToLeftLayout is true you should use GDI instead of GDI+. This means, you need to use TextRenderer class to display text, while RightToLeftLayout is true. On the other hand, if you use DrawString the text would be mirrored and not readable. A better incentive to use GDI is that it offers better performance and more accurate text measuring than GDI+.

With the introduction of RightToLeftLayout we need to examine two cases for text display. The first is when RightToLeftLayout=true and the second is when RightToLeftLayout=false.

Let's examine the first case, when RightToLeftLayout is set to true:

• You don't need to change the coordinates because the origin starts from the rightmost edge instead of the left edge of the drawing area.

• You don't need to set the rtl TextFormatFlags because they are set by default.

The following code snippets show how to display text when RightToLeftLayout=true and RightToLeft=yes:

[VB]

TextRenderer.DrawText(e.Graphics, " العربية !", Me.Font, New Rectangle(5, 5, 50, 50), SystemColors.ControlText)

[C#]

TextRenderer.DrawText(e.Graphics, " العربية !", this.Font, new Rectangle(5, 5, 50, 50), SystemColors.ControlText);

Let's examine the second case, when RightToLeftLayout is set to false:

• You need to calculate the correct left edge of your controls. Since the origin is still on the left and not on the right.

• You need to set the rtl TextFormatFlags because it is not set by default. You need to specify TextFormatFlags.RightToLeft .

The following code snippets show how to display text when RightToLeftLayout=false and RightToLeft=yes:

[VB]

'We have to adjust the left of the drawing rectangle to draw the text in the correct location
'NewLeft = FormWidth - (Left + Width)
TextRenderer.DrawText(e.Graphics, " العربية !", Me.Font, New Rectangle(Me.Width - (5 + 50), 5, 50, 50),
SystemColors.ControlText, TextFormatFlags.RightToLeft)

[C#]

// We have to adjust the left of the drawing rectangle to draw the text in the correct location
//NewLeft = FormWidth - (Left + Width)
TextRenderer.DrawText(e.Graphics, " العربية !", this.Font, new Rectangle(this.Width - (5+50), 5, 50, 50),
SystemColors.ControlText, TextFormatFlags.RightToLeft);