Introduction
This little piece of code implements animation using separated png files. It does start timer and renders image by frame you select. This is a good solution, because gif is not supported in Windows store application.
Using the Code
Just create a module and call function, but before using code, you must create png files in format
1.png,
2.png,
3.png, etc.
Imports Windows.UI.Xaml.Media.Animation
Imports Windows.UI
Imports Windows.UI.Xaml.Shapes
Module AnimationConstructor
Private _i As Integer = 0
Private _startFrame As Integer
Private _endFrame As Integer
Private _folderLocation As String
Private _X As Integer
Private _Y As Integer
Private _Form As Object
Private _sprite_explode As New Canvas
Private _explode As New Image
Private _myDispatcherTimer As New DispatcherTimer
Private _loopAnimation As Boolean
Public Function CreateAnimatedImage(Form As Object, ByVal X As Integer, _
ByVal Y As Integer, Optional folderLocation As String = "/sprite/explode/", _
Optional startFrame As Integer = 1, Optional endFrame As Integer = 24, _
Optional frameRate As Integer = 50, Optional loopAnimation As Boolean = False)
_i = startFrame
_endFrame = endFrame
_folderLocation = folderLocation
_X = X
_Y = Y
_Form = Form
_loopAnimation = loopAnimation
Try
_sprite_explode.Margin = New Thickness(_X, _Y, 0, 0)
_sprite_explode.Children.Add(_explode)
_Form.Children.Add(_sprite_explode)
_myDispatcherTimer.Interval = New TimeSpan(0, 0, 0, 0, frameRate)
AddHandler _myDispatcherTimer.Tick, AddressOf AnimationConstructor.Each_Tick
Catch ex As Exception
End Try
_explode.Visibility = Visibility.Visible
_myDispatcherTimer.Start()
End Function
Public Sub Each_Tick(ByVal sender As Object, ByVal e As EventArgs)
_i += 1
_explode.Source = BackgroundSource(_folderLocation + _i.ToString + ".png")
If _loopAnimation = True Then
If _i = _endFrame Then
Debug.WriteLine("Animation completed, reloading to start point")
_i = _startFrame
_explode.Visibility = Visibility.Visible
End If
Else
If _i = _endFrame Then
Debug.WriteLine("Animation complete")
_explode.Visibility = Visibility.Collapsed
_myDispatcherTimer.Stop()
_i = _startFrame
End If
End If
End Sub
Public Function BackgroundSource(sourceLocation As String)
Dim sourceImage As New BitmapImage
sourceImage = New BitmapImage(New Uri("ms-appx:///Assets" + sourceLocation))
Return sourceImage
End Function
End Module
Points of Interest
This is my first article post, this code is not perfect, but this is good point to start for beginners.
For usage, simply call:
CreateAnimatedImage(Me.Grid, 100, 150, "/sprite/explode/", 1, 24, 50)
me.grid
- our parent100, 150
x.y positions. - "/sprite/explode/" folder location
- in /explode/ you should paste image files
1
is starting image(1.png for example)24
is last image50
refresh rate(speed, lower value - faster)