VB.NET•Override OnPaint to Draw Photos and Maps

Listing 3. You must override the OnPaint event fired by the MyBase.Invalidate statement prior to painting the form with the image bitmap and overlaying optional gridlines to identify tile boundaries. This code redraws the image on the active area of the form and uses the System.Drawing.Imaging.DrawLine method to add white gridlines to photos and red gridlines to topo maps. You need additional code to add north-south and east-west image distance dimensions.

Protected Overrides Sub OnPaint( _
   ByVal e As PaintEventArgs)
   'Redraws the image every time the form is 
   If Not (bmpImage Is Nothing) Then
      'Redraw the bitmap on the form and 
      'add tile gridlines, if selected
         e.Graphics.DrawImage(bmpImage, 0, _
            0, bmpImage.Width, bmpImage.Height)
         If mnuThemeGridlines.Checked Then 
            'Draw tile grid lines on image
            Dim penLines As Pen
            If blnIsTopoMap Then
               'Red pen on topo maps
               penLines = New Pen(Color.Red, 2)
               'White pen on photos
               penLines = New Pen(Color.White, 2)
            End If
            'Process the horizontal and 
            'vertical line arrays
            Dim intCtr As Integer
            For intCtr = 0 To _
               UBound(aptfLinesHor, 1)
               'Draw the horizontal lines
               e.Graphics.DrawLine(penLines, aptfLinesHor( _
                  intCtr, 0), aptfLinesHor(intCtr, 1))
            For intCtr = 0 To _
               UBound(aptfLinesVert, 1)
               'draw the vertical lines
               e.Graphics.DrawLine(penLines, _
                  aptfLinesVert(intCtr, 0), _
                  aptfLinesVert(intCtr, 1))
            Next intCtr
         End If
      Catch excPaint As Exception
         Dim strMsg As String = _
            "Error in overridden " & _
            "OnPaint event handler."
         MsgBox(strMsg + excPaint.StackTrace, _
            MsgBoxStyle.Exclamation, _
            "OnPaint Exception")
      End Try
   End If
End Sub