PersistentGraphics

From HashVB
Revision as of 23:08, 6 November 2006 by E roder (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search
float
 This article is based on Visual Basic.NET. Find other Visual Basic.NET articles.

For those migrating from VB6 to VB.Net one noticeable change is the lack of an AutoRedraw property for Forms. If you try to draw to your form in .Net (using Me.CreateGraphics) you'll notice that your form flickers the image (or shape or text) you tried to draw and then returns to normal. There are two methods to draw persistently.

Your form may still flicker if you are drawing repeatedly to your form. If this is the case, read up on back buffers.

Method 1

Steps 1. Create an image in which to store your form's graphical data and a graphics object with which to draw on it, unfortunately the form has no Image property

'This code goes in the general section
Dim myBuffer As New Bitmap(Me.ClientSize.Width, Me.clientsize.height) 'a visual buffer to store our
'form's graphical data
Dim g as Graphics = Graphics.FromImage(myBuffer) 'create a Graphics object for us to draw with

2. Redraw your image buffer in the form's Paint method

Private Sub Form_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) _
Handles MyBase.Paint
        e.Graphics.DrawImage(myBuffer, 0, 0)
End Sub

3. Now, instead of drawing directly to your form, draw to the backbuffer first, then invalidate your form. Wherever you would write

Me.CreateGraphics.DrawString("Hubba Hubba", New Font("Tahoma", 12), New SolidBrush(Color.White), _
0, 0) 'For example

Instead write

g.DrawString("Hubba Hubba", New Font("Tahoma", 12), New SolidBrush(Color.White), 0, 0) 'Only an 
'example
Me.Invalidate 'This will force the form to call its Paint method

Method 2

This method is similar to Method One, but instead of having an image where you store your form's data, you have a method that does all the drawing for your form. This is the method you will want to use for games.

Steps 1. Write a method that will be in charge of the painting

Public Sub redrawScreen()
     Dim myBuffer As New Bitmap(Me.ClientSize.Width, Me.ClientSize.Height)
     Dim g As Graphics = Graphics.FromImage(myBuffer)
     g.FillRectangle(New SolidBrush(Color.Red), 0, 0, bBuffer.Width, bBuffer.Height)
     g.DrawString("Hubba Hubba", New Font("Tahoma", 12), New SolidBrush(Color.White), 0, 0)
     Me.CreateGraphics.DrawImage(myBuffer, 0, 0)
End Sub

2. Call your redrawScreen method in Form's Paint method

Private Sub Form_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) _
Handles MyBase.Paint
        redrawScreen()
End Sub