# [.net] Image Flickering

This topic is 3715 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Well from looking around at various sources and kind of guessing around with code, I've come up with this:
Public Class Form1
Public pos As Point = New Point(0, 0)
Public sprite As Image = Image.FromFile("green.bmp")
Public g As Graphics

Private Sub Form1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint
g = e.Graphics()
g.DrawImage(sprite, pos)
pos = New Point(pos.X + 1, pos.Y + 1)
End Sub

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Timer1.Interval = 20
Timer1.Enabled = True
End Sub

Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Me.Refresh()
End Sub
End Class
The Timer1.Tick event is to tell the Form to refresh (and call Form1_Paint) every 20 milliseconds, I added that in there because without it the image moved across the screen an an insanely fast rate. So now the problem I'm left with is that although this is working just fine, and I've also added some code to move the image around with the keys, the image is constantly flickering. I have no idea how to fix this though, could someone point me in the right direction? ---EDIT--- Well I talked to a friend who ran into a similar problem in Java and told me to look up a concept called DoubleBuffering. The cause of the flickering is that in my code, every 20ms the Form is cleared and then the image is drawn onto it again, so for a split second you can see when the image is not there (which causes the flickering). The way double buffering works is, rather than just clearing the screen, you have a temporary image that you clear, draw to it, then draw that to the screen, eliminating the actual clearing of the screen the user is looking at. Here's an example piece of code:
Public Class Form1
Public pos As Point = New Point(0, 0)
Public sprite As Image = Image.FromFile("green.bmp")
Public g As Graphics
Public temp As Bitmap = New Bitmap(Me.Width, Me.Height)
Public DrawingArea As Graphics = Graphics.FromImage(temp)

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Timer1.Interval = 20
Timer1.Enabled = True
End Sub

Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Timer1.Tick
g = Me.CreateGraphics()
DrawingArea.Clear(Me.BackColor())
DrawingArea.DrawImage(sprite, pos)
g.DrawImageUnscaled(temp, 0, 0)
pos = New Point(pos.X + 1, pos.Y + 1)
End Sub
End Class
[Edited by - Weebs on March 22, 2008 3:58:58 PM]

##### Share on other sites
For an even better idea, just set the DoubleBuffered property of the Form to true. Your control will then automatically use double buffering.

• 9
• 13
• 40
• 15
• 11