Use GDI+ System Brushes and Pens in VB.NET

In this article you will learn how to use System Brushes and Pens in GDI+.
  • 3141
 
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.

        Dim brush As SolidBrush = DirectCast(SystemBrushes.FormsSystemColor(SystemColors.ActiveCaption), SolidBrush)
        Dim pn As Pen = SystemPens.FromStystemColor(SystemColors.ControlDarkDark)

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

        Dim brush As SolidBrush = DirectCast(SystemBrushes.ActiveCaption, SolidBrush)
        Dim pn As Pen = 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:

pn.Dispose()
brush.Dispose()

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

LISTING 13.15: Using system pens and brushes

        Private Sub Form1_Paint(ByVal sender As Object, ByVal e As PaintEventArgs)
            Dim g As Graphics = e.Graphics
            'AVOID
            'SolidBrush brush =
            '            (SolidBrush) SystemBrushes.FromSystemColor
            '            (SystemColors.ActiveCaption);
            '           

            Dim brush As SolidBrush = DirectCast(SystemBrushes.ActiveCaption, SolidBrush)
            Dim pn As Pen = SystemPens.ControlDarkDark
            g.DrawLine(pn, 20, 20, 20, 100)
            g.DrawLine(pn, 20, 20, 100, 20)
            g.FillRectangle(brush, 30, 30, 50, 50)
            'Don't
            'pn.Dispose();
            'brush.Dispose();
        End Sub

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)
 
Figure2013_7.gif 

FIGURE 13.7: Using system pens and brushes

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.