Visual Basic .NET Language Create Graphic Object


There are three ways to create a graphics object

  1. From the Paint Event

Every time the control is redrawn (resized, refreshed...) this event is called, use this way if you want the control to consistently draw on the control

   'this will work on any object's paint event, not just the form
   Private Sub Form1_Paint(sender as Object, e as PaintEventArgs) Handles Me.Paint
     Dim gra as Graphics
     gra = e.Graphics
   End Sub
  1. Create Graphic

This is most often used when you want to create a one time graphic on the control, or you don't want the control to repaint itself

   Dim btn as New Button
   Dim g As Graphics = btn.CreateGraphics
  1. From an Existing Graphic

Use this method when you want to draw and change an existing graphic

   'The existing image can be from a filename, stream or Drawing.Graphic
   Dim image = New Bitmap("C:\TempBit.bmp")
   Dim gr As Graphics = Graphics.FromImage(image)