In VB.Net, trying to animate a vertical line that repeatably sweeps from left to right across a Picturebox

57 Views Asked by At

in VB.Net, I have a picturebox containing a graph like picture that looks like a grid. There are also various code drawn shapes in the picturebox that can be clicked by the user.. I'm trying to figure out a way of having a vertical line from top to bottom of the picturebox that moves across from left to right at a predetermined speed. I also need to able to determine when the line moved across a shape that he been clicked. Any suggestions would be appreciated. Many thanks.

I've solved the other problems mentioned and can produce a vertical line in the picturebox with simple code. But I'm stuck on trying to animate the line.

1

There are 1 best solutions below

6
jmcilhinney On

Here is an example of a vertical line that moves from left to right and starts again once it makes a full pass:

Private lineX As Integer = 0

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    lineX += 5

    If lineX > PictureBox1.Width Then
        lineX = 0
    End If

    PictureBox1.Invalidate()
End Sub

Private Sub PictureBox1_Paint(sender As Object, e As PaintEventArgs) Handles PictureBox1.Paint
    e.Graphics.DrawLine(Pens.Black,
                        New Point(lineX, 0),
                        New Point(lineX, PictureBox1.Height))
End Sub

The X coordinate of the line is stored in a field and that field is incremented on each Tick event of the Timer. The value is reset to zero once it reaches the right side of the PictureBox.

It's up to you what you set the Interval of the Timer to. A smaller value will obviously move the line faster. You can also vary the amount by which you increment the X coordinate. A smaller value will lead to a smoother animation. You'll need to balance those two values to get the speed and smoothness you want while not interfering noticeably with any other GUI operations.

Generally speaking, it is preferable to calculate the smallest area that may have changed on the control and specify that when you call Invalidate. The entire code in the Paint event handler is still executed but only the pixels within that area are repainted on screen and it's that last step that is the slowest part. I'll leave that as an exercise for you though. You would need to create the smallest Rectangle that contained both the old line and the new line so that area was repainted, erasing the old line and drawing the new line. At the point that the line reset to the left side, you could invalidate the whole control or you could call Invalidate twice - once for the old line on the right and once for the new line on the left. You can call Invalidate as many times as you like to repaint complex areas.