Using the brush / paint code / animate?

myblueocean

Well-known member
Joined
Jun 29, 2007
Messages
161
Location
England
Programming Experience
Beginner
Hi there,

I would like to know if you can animate the brush / paint code, so for example lets say you have a square and as soon as you run that program. The square moves to the left, with no interaction from you?
 
"'Draw a 200 pixel blue rectangle 20 pixels from the top of the form.
e.Graphics.DrawRectangle(Pens.blue, 10, 20, 20, 20)
'fill the square with a different colour.
e.Graphics.FillRectangle(Brushes.blue, 10, 20, 20, 20)"

This is the code, so how would I go about get this to move using a timer?
 
Try something like this:
VB.NET:
	Dim bmp As Bitmap = Nothing
	Dim RectSize As Rectangle = New Rectangle(0, 0, 100, 100)

	Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
		Me.Show()
		bmp = New Bitmap(Me.ClientRectangle.Width, Me.ClientRectangle.Height, Imaging.PixelFormat.Format32bppArgb)
		Using g As Graphics = Graphics.FromImage(bmp)
			Dim col As Color = Me.BackColor
			g.Clear(col)
		End Using
		For x As Integer = Me.ClientRectangle.Width + 10 To -110 Step -1
			DrawRectangle(New Point(x, (Me.ClientRectangle.Height - 100) / 2))
		Next
	End Sub

	Private Sub DrawRectangle(ByVal Loc As Point)
		RectSize.X = Loc.X
		RectSize.Y = Loc.Y
		Dim g As Graphics = Me.CreateGraphics()
		g.DrawImage(bmp, 0, 0)
		Dim pen As Pen = New Pen(Color.Red)
		g.DrawRectangle(pen, RectSize)
		g.Dispose()
		pen.Dispose()
		My.Application.DoEvents()
		Threading.Thread.Sleep(30)
	End Sub
 
Don't use CreateGraphics for drawing, use the Paint event. Force a Refresh/Invalidate if needed. You also shouldn't Sleep the UI thread.
 
I'm now kind of lost here...Um, I'm back to square one, so how do you get that small square to move in any direction you want once it has been debugged?
 
By providing the rectangle coordinate where you want it to draw and then calling for Refresh in order for Paint event to do its job repainting it at the new place.
 
"JohnH" Could you give me some example code? So I can type it in myself.
 
VB.NET:
Private drawRect As New Rectangle(0, 0, 50, 50)

Private Sub frmDiv_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint
    e.Graphics.DrawRectangle(Pens.DarkGreen, drawRect)
End Sub

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
    drawRect.Offset(1, 1)
    Me.Refresh()
End Sub
 
Back
Top