Gif 动画在 KeyPress 事件上停止

Gif animation is stopping on KeyPress event

我正在 Visual Studio 开发一款小型超级马里奥游戏。我拍了两张照片,第一张是站着的马里奥(png,不动),第二张是马里奥 运行(gif,3 帧)。问题是,当我一直按 "Right" 按钮时,gif 中的 3 帧只处理一次然后停止移动。

Private Sub Level1_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown
  Select Case e.KeyCode
    Case Keys.Right
      picBoxMario.Image = My.Resources.mario_running_right
  End Select
End Sub

Private Sub Level1_KeyUp(sender As Object, e As KeyEventArgs) Handles Me.KeyUp
  picBoxMario.Image = My.Resources.mario_standing_2
End Sub

插入一个布尔检查。所以,如果马里奥已经 运行ning,你就不会再 运行 :).
否则,您的 PictureBox 将继续仅显示第一帧,因为您不断地为其提供相同的动画。

(我假设 Level1FormKeyPreview = True

正如 Hans Passant 在评论中指出的那样,将这些 Image 资源分配给 class 对象是(不仅仅是)一个好主意,然后您可以在不再需要时 .Dispose() .

更新:根据评论,使用 class 对象的相等比较允许进一步简化动画状态检查。

Private MarioRunning As Image = My.Resources.mario_running_right
Private MarioStanding As Image = My.Resources.mario_standing_2

Private Sub Level1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    picBoxMario.Image = MarioStanding
End Sub

Private Sub Level1_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown
    Select Case e.KeyCode
        Case Keys.Right
            If picBoxMario.Image.Equals(MarioRunning) Then Return
            picBoxMario.Image = MarioRunning
    End Select
End Sub

Private Sub Level1_KeyUp(sender As Object, e As KeyEventArgs) Handles Me.KeyUp
    picBoxMario.Image = MarioStanding
End Sub

您可以使用 FormFormClosing()FormClosed() 事件来处理图像。

Private Sub Level1_FormClosed(sender As Object, e As FormClosedEventArgs) Handles MyBase.FormClosed
    If MarioRunning IsNot Nothing Then MarioRunning.Dispose()
    If MarioStanding IsNot Nothing Then MarioStanding.Dispose()
End Sub