Use System Brushes and Pens in GDI+

This article has been excerpted from book "Graphics Programming with GDI+".

You can always create system pens and system brushes with system colors by using the SystemColors class, but for performance reason it is advisable to use SystemPens and SystemBrushes instead of SystemColors. For example, the following code creates SolidBrush and Pen objects using SystemColors. The brush and pen have the ActiveCaption and ControlDarkDark system colors, respectively.

            SolidBrush brush =
            Pen pn = SystemPens.FromStystemColor

We can create the same brush and pen using the static methods of SystemBrushes and SystemPens, as the following code snippet illustrates:

            SolidBrush brush =
            Pen pn = SystemPens.ControlDarkDark;

Never dispose of system pens and brushes. Any attempt to do so will result in an unhandled exception. For example, adding the following two lines to the code will throw an exception:


Listing 13.15 shows the complete code of a form's paint event handler.

LISTING 13.15: Using system pens and brushes

        private void Form1_Paint(object sender, PaintEventArgs e)
            Graphics g = e.Graphics;
            /* SolidBrush brush =
            (SolidBrush) SystemBrushes.FromSystemColor
            SolidBrush brush =
            Pen pn = SystemPens.ControlDarkDark;
            g.DrawLine(pn, 20, 20, 20, 100);
            g.DrawLine(pn, 20, 20, 100, 20);
            g.FillRectangle(brush, 30, 30, 50, 50);

Figure 13.7 shows the output from Listing 13.5. The lines and rectangle are drawn with system colors.

Avoid Automatic Scaling of Images

Automatic scaling could result in performance degradation. If possible, avoid automatic scaling. The DrawImage method takes a Bitmap object and a rectangle with upper left corner position and specified width and height. If we pass only the upper left corner position, GDI+ may scale the image, which decreases performance. For example, the code

e.Graphics.DrawImage (image, 10, 10);

can be replaced with the following code:

e.Graphics.DrawImage (image, 10, 10, image.Width, image.Height);

Figure 13.7.gif

FIGURE 13.7: Using system pens and brushes