- Basic Text Display
- Windows Fonts
- Font Class
- Displaying Text
- Other Format Settings
Displaying Text
You saw in the example earlier in this article that you use the Graphics.DrawString() method to display text. In that example, the coordinates were specified as an X (horizontal) and Y (vertical) position of the top-left corner of the text. You can also use a PointF structure for the same purpose:
PointF p = new PointF(25, 25); g.DrawString(msg, f, br, p);
With coordinates specified in this way, the text will extend off the right edge of the window if it is too long. Look at the following code and the output in Figure 3:
Font f = new Font("Times", 24); SolidBrush br = (SolidBrush)Brushes.Black; Graphics g = e.Graphics; string msg = "This is a rather long message to display"; PointF p = new PointF(25, 25); g.DrawString(msg, f, br, p);
Figure 3 When position is specified as an X,Y position, text can extend off the form.
If you want to avoid this, specify the text position as a RectangleF structure. The text is not only positioned at the top-left corner of the rectangle but also is wrapped if needed to remain within the rectangle. Here’s a code example, with the output shown in Figure 4 (I added a line of code to display the rectangle):
Font f = new Font("Times", 24); SolidBrush br = (SolidBrush)Brushes.Black; Graphics g = e.Graphics; string msg = "This is a rather long message to display"; RectangleF r = new RectangleF(25f, 25f, 150f, 200f); g.DrawString(msg, f, br, r); g.DrawRectangle(Pens.Black, Rectangle.Truncate(r));
Figure 4 When position is specified as a RectangleF structure, text wraps to fit within the rectangle.