Reputation: 394
I have an animated gif in a PictureBox on my form but it is always looping, how can I make it only play once?
When viewing the gif in another program (eg a browser) it only plays once, as it should. However on my form it loops all the time with only a very short jerky pause between loops of the animation.
Upvotes: 3
Views: 6823
Reputation: 31
Here's a fairly simple solution. I created a timer for the total combined time of one loop of the animated gif. When the timer stops it changes the image to a still picture in the picture box.
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
Upvotes: 1
Reputation: 1069
That took me a while... Here I obtain number of frames and animate the gif until the end of frames.
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
Upvotes: 5
Reputation: 44931
If you can determine how long the cycle is, you can stop the animation by disabling the picturebox after the appropriate amount of time.
EDIT: After reviewing the PictureBox source code, it doesn't look like there is a way to modify this behavior in the PictureBox itself.
However, there does appear to be a viable alternative: the ImageAnimator class, which is what the PictureBox uses internally. The MSDN article has a good sample of how to animate one time.
Upvotes: 1