Visual Basic 2005 with .NET 3.0 Programmer's Reference
Before jumping into GDI+ graphics, it’s worth taking a moment to learn which namespaces contain which objects. By default, the System.Drawing namespace is imported into new applications automatically, so you don’t need to explicitly import it to work with Graphics, Pen, Brush, and the other basic drawing objects. However, if you want to create custom dash patterns (long dashes, dot-dash-dot), linear gradient color fills (shading from one color to another and possibly to others), or advanced image files (JPEG, GIF, TIFF), you must know which namespaces to import into your application.
System.Drawing
The System.Drawing namespace contains the most important and basic GDI+ classes. These classes include Graphics, Pen, Brush, Font, FontFamily, Bitmap, Icon, and Image. The following table describes the most useful System.Drawing classes.
Class | Description |
---|---|
Graphics | This is without doubt the most important object you’ll use when creating graphics. A Graphics object represents the surface you’re going to draw on. That could be a PictureBox, form, bitmap in memory, or whatever. The Graphics object provides the methods for drawing lines, rectangles, ellipses, and so forth. |
Pen | This class represents the drawing characteristics of a line, including the line’s color, thickness, dash style, and so forth. |
Pens | This class provides a large number of predefined pens with different colors and width 1. For example, you can use Pens.Blue as a standard blue pen. |
Brush | This class represents how solid areas are filled. It determines whether the area is solidly colored, hatched, filled with a pattern, and so on. |
Brushes | This class provides a large number of predefined solid brushes with different colors. For example, you can use Brushes.Green to fill an area with green. |
SolidBrush | This class represents a solid brush. When you want to fill an object with a solid color, you use a SolidBrush class. This is by far the most common type of fill for most applications. |
Bitmap | This class represents a bitmap image defined by pixel data rather than drawn lines. |
Icon | This class represents a Windows icon similar to a bitmap. |
Metafile | This class represents a graphic metafile that contains graphical operations that a program can record, save to a file, load from a file, and play back later. |
Image | This is an abstract base class from which Bitmap, Icon, and Metafile inherit. Some routines can work with any of these kinds of objects, so they take an Image parameter. (In brief, a bitmap is a typical picture. An icon has additional transparency and possibly hot-spot information so it can act as a form or application icon or mouse pointer. A metafile contains drawing instructions that some applications can use to scale the picture smoothly.) |
Font | This class represents a particular font. It defines the font’s name, size, and style (such as italic or bold). |
FontFamily | This class represents a group of typefaces with similar characteristics. |
Region | This class defines a shape created from rectangles and paths. You can fill a region, use it to perform hit testing, or clip a drawing to a region. |
The System.Drawing namespace also defines some structures that a program can use for drawing. The following table describes the most useful of these structures.
Structure | Description |
---|---|
Color | This object defines a color’s red, green, and blue components as values between 0 and 255, plus an alpha value that indicates the color’s transparency. An alpha value of 0 means the object is completely transparent, while a value of 255 means it is totally opaque. |
Point | This object defines a point’s X and Y coordinates. |
Size | This object defines a width and height. |
Rectangle | This object defines a rectangle using a Point and a Size. |
GDI+ routines work in pixels on the screen, printer, or whatever object they are drawing on, so the Point, Size, and Rectangle structures hold integral coordinates and sizes. However, the System .Drawing namespace also defines PointF, SizeF, and RectangleF classes to work with floating-point values.
The Color class provides a large number of predefined color values. For example, Color.PaleGreen defines a light green color. You can use these predefined colors instead of creating a new color object.
System.Drawing.Drawing2D
The System.Drawing.Drawing2D namespace contains most of the other objects you’ll need to draw more advanced two-dimensional graphics. Some of these classes refine the more basic drawing classes, or define values for those classes. For example, the HatchBrush class represents a specialized type of Brush that fills with a hatch pattern. The following table describes this namespace’s most useful classes.
Class | Description |
---|---|
HatchBrush | This class defines a Brush that fills an area with a hatch pattern. It defines the pattern, a foreground color, and a background color. |
LinearGradientBrush | This class defines a Brush that fills an area with a linear color gradient. By default the fill shades smoothly from one color to another along a line that you define, but it can also represent multicolor gradients. (Chapter 21 has more to say about the LinearGradientBrush class, and Figure 21-11 shows some examples.) |
Blend | This class represents a blend pattern for a LinearGradientBrush or PathGradientBrush. For example, suppose that you define a gradient running from red to yellow. Normally the gradient is smooth and linear, but you can use a Blend to change this. For example, you might want the color to change from red to yellow very quickly, so it is 80 percent yellow only 20 percent of the way across the gradient. (The effects of Blend are subtle but you can see them in Figure 21-11.) |
PathGradientBrush | This class is similar to a LinearGradientBrush except its gradient follows a path rather than a line. (Figure 21-12 shows some examples.) |
ColorBlend | This class defines colors and positions for LinearGradientBrush or PathGradientBrush. This lets you make the colors vary between several different colors along the brush’s path. (Figure 21-11 shows an example.) |
GraphicsPath | This class represents a series of connected lines and curves. You can draw, fill, or clip to a GraphicsPath. For example, you could add text to a GraphicsPath and then draw its outline or clip a drawing so that it only shows within the text’s path. (Figure 21-13 shows a GraphicsPath filled with TextureBrush.) |
Matrix | This class represents a 3 × 3 transformation matrix. You can use matrixes to translate, scale, and rotate graphics operations. See the section “Transformation Basics” later in this chapter for more information. |
The System.Drawing.Drawing2D namespace also defines some enumerations that are useful for more advanced drawing. The following table describes the most useful of these enumerations.
Enumeration | Description |
---|---|
DashCap | These values determine how the ends of a dash in a dashed line are drawn. DashCap values include Flat, Round, and Triangle. These give the same appearance as the Flat, Round, and Triangle LineCap enumerations shown in Figure 20-2. |
DashStyle | These values determine how a dashed line is drawn. DashStyle values include Dash, DashDot, DashDotDot, Dot, Solid, and Custom. If you set a Pen’s DashStyle property to DashStyle.Custom, then you should also set its DashPattern property to an array telling the Pen how many to pixels to draw and skip. For example, the array {10, 20, 5, 2} means draw 10, skip 2, draw 5, skip 2, and then repeat as necessary. |
LineCap | These values determine how the ends of a line are drawn. Values include ArrowAnchor, DiamondAnchor, Flat, NoAnchor, Round, RoundAnchor, Square, SquareAnchor, Triangle, and Custom. If LineCap is Custom, you should use a CustomLineCap object to define the cap. Figure 20-2 shows the standard LineCaps. |
LineJoin | These values determine how lines are joined by a GDI+ method that draws connected lines. For example, the DrawPolygon and DrawLines methods use this property. Figure 20-3 shows the possible values Bevel, Miter, Round, and MiterClipped. MiterClipped produces either a mitered or beveled corner, depending on whether the miter’s length exceeds a certain limit determined by the Pen class’s MiterLimit property. The MiterClipped example in Figure 20-3 shows one join that exceeds this limit and one that does not. |
HatchStyle | These values define the hatch style used by a HatchBrush object to fill an area. This enumeration includes 54 values, so they are not all listed here. Figure 20-4, however, lists them and shows samples. |
System.Drawing.Imaging
The System.Drawing.Imaging namespace contains classes that deal with more advanced bitmap graphics. It includes classes that define image file formats such as GIF and JPG, classes that manage color palettes, and classes that define metafiles. The following table describes this namespace’s most useful classes.
Class | Description |
---|---|
ImageFormat | This class specifies an image’s format. This can be one of BMP, EMF, EXIF, GIF, ICON, JPEG, memory bitmap, PNG, TIFF, or WMF. For descriptions of these image format types, try searching for them at web sites such as Webopedia (www.webopedia.com). The page www.webopedia.com/DidYouKnow/Internet/2002/JPG_GIF_ PNG.asp discusses the differences between the three most common Web image formats: GIF, JPEG, and PNG. The Microsoft web site has a comparison of the BMP, GIF, JPEG, Exif, PNG, and TIFF formats at msdn.microsoft.com/library/en-us/gdicpp/ GDIPlus/aboutGDIPlus/imagesbitmapsandmetafiles/ typesofbitmaps.asp. |
ColorMap | This class defines a mapping from old color values to new ones. You can use the ColorMap class to change some colors in an image to others. |
ColorPalette | This class represents a palette of color values. (A palette is a collection of color values that are used in a particular image. For example, 8-bit color images can contain only 256 different colors. The image’s color palette lists the colors used, and an 8-bit numeric value gives each pixel’s color index in the palette. Recently, higher color models such as 16-, 24-, and 32-bit color have become more common. In those color models, the bits give each pixel’s red, green, and blue color components directly rather than referring to a color palette, so no palette is needed.) |
Metafile | This class represents a graphic metafile that contains drawing instructions. You can create, save, reload, and play back metafile information. |
MetafileHeader | This class defines the attributes of a Metafile object. (A metafile lets a program define a drawing in terms of lines, curves, and filled areas rather than using pixels in a bitmap. This lets the program later redraw the image scaled, rotated, or otherwise transformed smoothly without the distortion that would occur in a bitmapped image.) |
MetaHeader | This class contains information about a Windows metafile (WMF). |
WmfPlaceableFileHeader | This class defines how a metafile should be mapped to an output device. You can use this to ensure that the metafile is properly sized when you import it into a drawing program such as CorelDRAW .System.Drawing.Text |
The System.Drawing.Text namespace contains only three classes. These three classes provide a somewhat awkward method for learning about the fonts installed on the system or the fonts installed for an application. The following table describes these three classes.
Class | Description |
---|---|
FontCollection | A base class for the derived InstalledFontCollection and PrivateFontCollection classes. It provides a method that returns an array of FontFamily objects. |
InstalledFontCollection | This is derived from the FontCollection class. This class’s Families method returns an array containing FontFamily objects representing the fonts installed on the system. |
PrivateFontCollection | This is also derived from the FontCollection class. Objects from this class represent fonts installed by an application from font files. The program can use this object to install fonts just for the use of the application and not for the rest of the system. This class provides methods for installing and listing the application’s fonts. |
It is rather odd that this class is defined just to provide one method that returns an array of FontFamily objects. It would have made more sense to give the FontCollection class a method such as List?InstalledFonts or to give the InstalledFontCollection class a shared method that creates such a FontCollection object. That’s not the way these classes work, however.
To list the system’s fonts, a program creates an instance of the InstalledFontCollection and uses that object’s Families method to get an array of the installed FontFamily objects. The program can then loop through the array to list the fonts. The following code demonstrates this method:
Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ' Get the installed fonts collection. Dim installed_fonts As New InstalledFontCollection ' Get an array of the system's font familiies. Dim font_families() As FontFamily = installed_fonts.Families() ' Display the font families. For Each font_family As FontFamily In font_families lstFonts.Items.Add(font_family.Name) Next font_family lstFonts.SelectedIndex = 0 End Sub
Figure 20-5 shows the result.
The System.Drawing.Text namespace also defines the TextRenderingHint enumeration. Anti-aliasing is a process that uses pixels of different shades to make jagged edges and curves appear smoother. You can set a Graphics object’s TextRenderingHint property to tell Visual Basic whether it should use antialiasing to smooth the text. The following table describes the TextRenderingHint enumeration values.
Enumeration Value | Description |
---|---|
AntiAlias | Characters are drawn anti-aliased without hinting. |
AntiAliasGridFit | Characters are drawn anti-aliased with hinting to improve stems and curves. |
ClearTypeGridFit | Characters are drawn using ClearType glyphs with hinting. This takes advantage of ClearType font features. (In this context, a glyph is the image of a letter. Some fonts are drawn as glyphs and others such as TrueType fonts are drawn as outlines. TrueType was developed jointly by Microsoft and Apple. ClearType is a newer type of glyph font developed by Microsoft.) |
SingleBitPerPixel | Characters are drawn without anti-aliasing or hinting. This is the fastest and lowest-quality setting. |
SingleBitPerPixelGridFit | Characters are drawn without anti-aliasing, but with hinting. |
SystemDefault | Characters are drawn using the system default setting. |
The following code shows how a program can display text with and without anti-aliasing. First it creates a large font. It sets the Graphics object’s TextRenderingHint property to AntiAliasGridFit and draws some text. Then it sets TextRenderingHint to SingleBitPerPixel and draws the text again.
Private Sub Form1_Paint(ByVal sender As Object, _ ByVal e As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint ' Make a big font. Using the_font As New Font(Me.Font.FontFamily, _ 40, FontStyle.Bold, GraphicsUnit.Pixel) ' Draw without anti-aliasing. e.Graphics.TextRenderingHint = TextRenderingHint.AntiAliasGridFit e.Graphics.DrawString("Alias", _ the_font, Brushes.Black, 5, 5) ' Draw with anti-aliasing. e.Graphics.TextRenderingHint = TextRenderingHint.SingleBitPerPixel e.Graphics.DrawString("Alias", _ the_font, Brushes.Black, 5, 50) End Using End Sub
Figure 20-6 shows the result, greatly enlarged to emphasize the difference. Notice how the anti-aliased version uses different shades of gray to make the text appear smoother.
System.Drawing.Printing
The System.Drawing.Printing namespace contains objects for printing and managing the printer’s characteristics.
Normally, to generate a printed document, you create a PrintDocument object. You set the object’s properties to define printing attributes and then call its Print method. As it prints, the PrintDocument object generates PrintPage events that let you draw on the printout’s pages.
Other classes in this namespace define properties for the PrintDocument object. The following table describes the most useful of these property objects.
Class | Description |
---|---|
PageSettings | This class defines the page settings for either an entire PrintDocument or for a particular page. This object has properties that are Margins, PaperSize, PaperSource, PrinterResolution, and PrinterSettings objects. |
Margins | This class defines the margins for the printed page through its Top, Bottom, Left, and Right properties. |
PaperSize | This class defines the paper’s size. You can set the object’s Kind property to a standard value such as A2, Legal, or Letter. Alternatively, you can set the object’s Height and Width properties explicitly. |
PaperSource | This class defines the printer’s paper source. You can set this object’s Kind property to such values as AutomaticFeed, Upper, Middle, Lower, Envelope, and ManualFeed. |
PrinterResolution | This class defines the printer’s resolution. |
PrinterSettings | This class defines the printer’s settings. You can use this class to get setting values such as whether the printer can print double-sided (CanDuplex), the names of the installed printers (InstalledPrinters), and the printer’s supported resolutions (PrinterResolutions). You can use other properties to control the printer. For example, you can set the number of copies (Copies), set the minimum and maximum page number the user can select in a print dialog (MinimumPage and MaximumPage), and determine whether the printer collates its output (Collate). |
Категории