10.13 Displaying Text

 <  Day Day Up  >  

You want to display a string of text using a specified font.


Technique

To render text, you must first create a Font object. The Font class contains several different constructors, allowing you to control precisely how the font should appear. You can also use the different member methods within the Font class to manipulate the font after it is created. In most cases, you want to specify a FontFamily , which can be found within the InstalledFontCollection object described in the last recipe, or an equivalent string value representing the name of the font. You may also specify the size of the Font using a float value, which by default is specified in points. You can change the unit of measurement from points to a different unit by specifying a GraphicsUnit value. To add bold, italic, underline, or other style, use a logical OR of the values defined in the FontStyle enumeration:

 
 FontStyle fs = 0; if( menuBold.Enabled == true && bold == true )     fs = FontStyle.Bold; if( menuItalic.Enabled == true && italic == true )     fs = FontStyle.Italic; if( menuUnderline.Enabled == true && underline == true )     fs = FontStyle.Underline; Font f = new Font( cbFonts.SelectedItem.ToString(), 12.0f, fs ); 

To render a string to the current drawing surface, call the DrawString method defined in the Graphics class. The first parameter is the string you want to render. The second parameter to the method is the Font object created earlier. The additional parameters are the type of Brush to use and the bounding rectangle to render the text to.

 
 e.Graphics.DrawString( "C# Font Test", f,     new SolidBrush( Color.Black ), panel1.DisplayRectangle); 

Comments

The previous recipe noted that you create a Font object by specifying a font family name, font styles, and the point size of the font. Once this object is created, you can call the DrawString method to render a string to the associated rendering surface. You can additionally associate a StringFormat object with the DrawString method to support such things as right-to-left rendering using the Alignment property; vertical text, which you do by adding the DirectionVertical flag to the FormatFlags property; and the hotkey prefix, which creates an underlined character indicating a keyboard shortcut. You make a hotkey by setting the HotKeyPrefix property to either Hide , None , or Show .

 <  Day Day Up  >  


Microsoft Visual C# .Net 2003
Microsoft Visual C *. NET 2003 development skills Daquan
ISBN: 7508427505
EAN: 2147483647
Year: 2003
Pages: 440

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