Simple Text Example


This example, DisplayText, is your usual Windows Forms effort. This time you override OnPaint() and add member fields as follows:

  private Brush blackBrush = Brushes.Black; private Brush blueBrush = Brushes.Blue; private Font haettenschweilerFont = new Font("Haettenschweiler", 12); private Font boldTimesFont = new Font("Times New Roman", 10, FontStyle.Bold); private Font italicCourierFont = new Font("Courier", 11, FontStyle.Italic |    FontStyle.Underline); protected override void OnPaint(PaintEventArgs e) {    base.OnPaint(e);    Graphics dc = e.Graphics;    dc.DrawString("This is a groovy string", haettenschweilerFont, blackBrush,                  10, 10);    dc.DrawString("This is a groovy string " +                  "with some very long text that will never fit in the box",                  boldTimesFont, blueBrush,                  new Rectangle(new Point(10, 40), new Size(100, 40)));    dc.DrawString("This is a groovy string", italicCourierFont, blackBrush,                  new Point(10, 100)); } 

Figure 30-15 shows the result of running this example.

image from book
Figure 30-15

The example demonstrates the use of the Graphics.DrawString() method to draw items of text. The method DrawString() comes in a number of overloads, three of which are demonstrated here. The different overloads require parameters that indicate the text to be displayed, the font that the string should be drawn in, and the brush that should be used to construct the various lines and curves that make up each character of text. A couple of alternatives exist for the remaining parameters. In general, however, it is possible to specify either a Point (or equivalently, two numbers) or a Rectangle.

If you specify a Point, the text will start with its top-left corner at that Point and simply stretch out to the right. If you specify a Rectangle, then the Graphics instance will lay out the string inside that rectangle. If the text doesn’t fit within the boundaries of the rectangle, it’ll be cut off (see the fourth line of text in Figure 30-15). Passing a rectangle to DrawString() means that the drawing process will take longer, because DrawString() will need to figure out where to put line breaks, but the result may look nicer, provided the string fits in the rectangle!

This example also shows a couple of ways of constructing fonts. You always need to include the name of the font and its size (height). You can also optionally pass in various styles that modify how the text is to be drawn (bold, underline, and so on).




Professional C# 2005 with .NET 3.0
Professional C# 2005 with .NET 3.0
ISBN: 470124725
EAN: N/A
Year: 2007
Pages: 427

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net