2016-11-24 59 views
0

我目前正在編寫一個小動畫。動畫以一個小圓圈在屏幕上移動開始,然後用戶單擊按鈕和其他小圖片在屏幕上移動(我感覺像描述圖像的內容,程序的目的等將是切向和不相關的)。有沒有辦法爲多個程序使用計時器滴答?

我目前編碼動畫的方式是這樣的:

Private Sub Timer_Tick(sender As Object, e As EventArgs) Handles Timer.Tick 
    Circle1.Left -= 10 
    If Counter = 16 Then 
     Timer.Enabled = False 
     Counter = 0 
    End If 
    Counter += 1 
End Sub 

然而,問題是,我需要使用計時器,以幫助動畫多個圖像的運動。除了創建多個定時器之外,還有一種在多個子程序中使用定時器滴答的方法嗎?

+0

有超過你更新,然後只是Circle1.Left。你做什麼完全取決於你,我們無法猜測。 –

+0

什麼阻止你在'timer_tick'中添加其他圖像? –

回答

0

您可以使用列表來保存所有要設置動畫的控件。迭代計時器事件中的列表並修改控件的位置。這裏有一個例子如何做到這一點。

Public Class Form1 

    ' this list holds all controls to animate 
    Private controlsToAnimate As New List(Of Control) 

    Private random As New Random 

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick 

     ' this list holds all controls to remove 
     Dim controlsToRemove As New List(Of Control) 

     For i = 0 To controlsToAnimate.Count - 1 
      Dim control = controlsToAnimate(i) 
      If control.Left < 0 Then 
       ' this control has reached the left edge, so put it in the list to remove 
       controlsToRemove.Add(control) 
      Else 
       ' move the control to left 
       control.Left -= 10 
      End If 
     Next 

     ' remove all controls that have reached the left edge 
     For Each control In controlsToRemove 
      controlsToAnimate.Remove(control) 
      control.Dispose() 
     Next 

     ' for debug only, display the number of controls to animate 
     Me.Text = controlsToAnimate.Count() 

    End Sub 

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 

     ' create a new picturebox 
     Dim newControl As New PictureBox 
     With newControl 
      ' load an image for the picturebox 
      .Image = Image.FromFile("D:\Pictures\abc.jpg") 

      ' size of the picturebox 
      .Size = New Size(100, 100) 

      ' picturebox appears at the right edge of the form, 
      ' the vertical position is randomize 
      .Location = New Point(Me.Width - newControl.Width, random.Next(Me.Height - newControl.Height)) 

      ' stretch the image to fit the picturebox 
      .SizeMode = PictureBoxSizeMode.StretchImage 
     End With 

     ' add the newly created control to list of controls to animate 
     controlsToAnimate.Add(newControl) 

     ' add the newly created control to the form 
     Me.Controls.Add(newControl) 

    End Sub 

End Class 
相關問題