Tuesday, 11 December 2012

Grid on a .NET form

I needed to place a grid on the main form in a .NET application, the grid is a height field that I am generating for a random terrain generator.

When the form is loaded, the nMap class is instantiated with some definition stuff. The nMap class is where I process the grid of data representing the map cells. There is some processing stuff in the class that sets the RGB values for each of the cells.

Public Sub drawGrid(Optional ByVal minLines As Boolean = True, Optional ByVal majLines As Boolean = True)
        Dim cellRef As Long = 1024
        PictureBox1.Image = New Bitmap((CInt(nMap.width) * 10) + 20, (CInt(nMap.height) * 10) + 20)
        Using g As Graphics = Graphics.FromImage(PictureBox1.Image)
            Dim grayPen As New Drawing.Pen(Color.Gray)
            Dim blackPen As New Drawing.Pen(Color.Black)
            'cellcolour
            For i As Long = 0 To (nMap.width * nMap.height) - 1
                cellRef = i
                Dim nColour As New Color
                'Dim nAry As cellRGB = nMap.grid(i)
                'nColour = Color.FromArgb(nAry.R, nAry.G, nAry.B)
                Dim nAry() As String = nMap.grid(i).ToString.Split(":")
                nColour = Color.FromArgb(nAry(0), nAry(1), nAry(2))

                Dim nBrush = New SolidBrush(nColour)
                Dim X1, Y1 As Long
                X1 = 10 + ((cellRef - (Int(cellRef / nMap.width) * nMap.width)) * 10)
                Y1 = 10 + (Int(cellRef / nMap.width) * 10)
                g.FillRectangle(nBrush, New Rectangle(X1, Y1, 10, 10))
            Next

            Dim x As Integer
            Dim y As Integer

            Dim intSpacing As Integer = 10
            x = PictureBox1.Width

            'gridlines - minor gridlines
            If minLines Then
                For y = 10 To PictureBox1.Height - 10 Step intSpacing
                    g.DrawLine(grayPen, New Point(10, y), New Point(x - 10, y))
                Next
                y = PictureBox1.Height
                For x = 10 To PictureBox1.Width - 10 Step intSpacing
                    g.DrawLine(grayPen, New Point(x, 10), New Point(x, y - 10))
                Next
            End If
            'gridlines - major gridlines
            intSpacing = 100

            If majLines Then
                For y = 10 To PictureBox1.Height - 10 Step intSpacing
                    g.DrawLine(blackPen, New Point(10, y), New Point(x - 10, y))
                Next
                y = PictureBox1.Height
                For x = 10 To PictureBox1.Width - 10 Step intSpacing
                    g.DrawLine(blackPen, New Point(x, 10), New Point(x, y - 10))
                Next
            End If
        End Using
    End Sub

The Major and Minor gridlines can be turned on and off as suits. This happens in the redraw function.

No comments:

Post a Comment

Paypal Donations

Donations to help me to keep up the lunacy are greatly appreciated, but NOT mandatory.