我在窗体上的PictureBox中有一个动画GIF,但它总是循环播放,我怎么才能让它只播放一次?动画GIF不会停止循环Winforms
在其他程序(例如浏览器)中查看gif时,它只会播放一次,因为它应该。然而,在我的表单中,它始终循环,动画的循环之间只有很短暂的停顿。
我在窗体上的PictureBox中有一个动画GIF,但它总是循环播放,我怎么才能让它只播放一次?动画GIF不会停止循环Winforms
在其他程序(例如浏览器)中查看gif时,它只会播放一次,因为它应该。然而,在我的表单中,它始终循环,动画的循环之间只有很短暂的停顿。
我花了一段时间...在这里,我获取帧的数量和动画的GIF,直到帧的结束。
Public Class Form1
Dim animatedImage As New Bitmap("a.gif")
Dim currentlyAnimating As Boolean = False
Dim framecounter As Integer = 0
Dim framecount As Integer
Dim framdim As Imaging.FrameDimension
Private Sub OnFrameChanged(ByVal o As Object, ByVal e As EventArgs)
PictureBox1.Invalidate()
End Sub
Sub AnimateImage()
If Not currentlyAnimating Then
ImageAnimator.Animate(animatedImage, New EventHandler(AddressOf Me.OnFrameChanged))
currentlyAnimating = True
End If
End Sub
Private Sub PictureBox1_Paint(sender As Object, e As System.Windows.Forms.PaintEventArgs) Handles PictureBox1.Paint
If framecounter < framecount Then
AnimateImage()
ImageAnimator.UpdateFrames()
e.Graphics.DrawImage(Me.animatedImage, New Point(0, 0))
framecounter += 1
End If
End Sub
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
framdim = New Imaging.FrameDimension(animatedImage.FrameDimensionsList(0))
framecount = animatedImage.GetFrameCount(framdim)
End Sub
End Class
如果您可以确定周期的长度,则可以在适当的时间后禁用图片框来停止动画。
编辑:审查PictureBox源代码后,它看起来不像有一种方法来修改图片框本身的这种行为。
但是,似乎确实存在一个可行的替代方案:ImageAnimator类,这是PictureBox内部使用的类。 MSDN文章有一个如何动画的好例子。
尝试过,但帧之间只有100ms,很难确保它在完全正确的位置停下来。一帧关闭,看起来不对。 – Sparrowhawk
@ Sparrowhawk:更新了答案,以包含我发现的其他信息和其他方法。 –
这是一个相当简单的解决方案。我为动画GIF的一个循环的总组合时间创建了一个计时器。当定时器停止时,它将图像更改为图像框中的静止图像。
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
PictureBox1.Image = Image.FromFile("c:\GIF\AnimatedGif.gif")
Timer1.Enabled = True
End Sub
Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) Handles Timer1.Tick
PictureBox1.Image = Image.FromFile("c:\GIF\StillImage.gif")
Timer1.Enabled = False
End Sub
感谢你们两位!基本上相同的答案:) – Sparrowhawk