我最近问了一个问题,如何让垂直线从左到右扫过图片框。图片框中有一些形状,垂直线必须表明它何时穿过形状。 我有一个非常有效的答案。
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
但是,我发现当我在图片框中移动鼠标时,垂直线会停止、开始或减慢。从网上看,我认为不同线程上的计时器可能是答案。
有人可以建议解决这个问题吗?
提前非常感谢。
您可以通过考虑有效经过的时间来提高运动的准确性:
Private lastDateTime As Date?
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Dim now = Date.Now
If lastDateTime.HasValue Then
lineX += CInt(5 * (lastDateTime.Value - now).Milliseconds / Timer1.Interval)
Else
lineX += 5
End If
lastDateTime = now
If lineX > PictureBox1.Width Then
lineX = 0
End If
PictureBox1.Invalidate()
End Sub