Most drawing in .NET occurs in the context of a Graphics object. (For those familiar with pre-.NET development in Windows, this is similar to a device context.) Graphics objects provide a canvas on which you draw lines, shapes, bitmap images, and pre-recorded drawing macros. Graphics objects do not contain the graphics surface itself; they are simply generic conduits to the actual canvas. There is always some surface behind the Graphics object, whether it is a portion of the screen, a Bitmap object, or the simulated surface of a printed page. Any drawing that is done to the Graphics object immediately impacts the underlying surface.
The Graphics object includes dozens of methods that let you draw shapes and images on the graphics surface, and perform other magical 2-D activities. We'll cover many of them in this chapter.
Obtaining and Creating Graphics Objects
Getting a Graphics object for an on-screen form or control is as easy as calling the form or control's CreateGraphics method.
Dim wholeFormGraphics As Graphics = _ Form1.CreateGraphics() Dim buttonOnlyGraphics As Graphics = _ Button1.CreateGraphics()
Some events, most notably the Paint event for forms and controls, provide access to a Graphics object through the event arguments.
Private Sub PictureBox1_Paint(ByVal sender As Object, _ ByVal e As System.Windows.Forms.PaintEventArgs) _ Handles PictureBox1.Paint Dim holdGraphics As Graphics = e.Graphics End Sub
You can also create a Graphics object that is unrelated to any existing display area by associating it to a bitmap.
Dim workBitmap As New Bitmap(50, 50) Dim workGraphics = Graphics.FromImage(workBitmap)
Remember, all changes made to the workGraphics instance will impact the workBitmap image.
Disposing of Graphics Objects Properly
When you are finished with a Graphics object that you create, you must dispose of it by calling its Dispose method. (This rule is true for many different GDI+ objects.) Don't keep it around for a rainy day because it won't be valid later. You must, must, must dispose of it when you are finished with it. If you don't, it could result in image corruption, memory usage issues, or worse yet, international armed conflict. So, please dispose of all Graphics objects properly.
If you create a Graphics object within an event, you really need to dispose of it before exiting that event handler. There is no guarantee that the Graphics object will still be valid in a later event. Besides, it's easy to re-create another Graphics object at any time.
If you use a Graphics object that is passed to you from another part of the program (like that e.Graphics reference in the preceding Paint event handler), you should not dispose of it. Each creator is responsible for disposing of its own objects.