Sample.AnimatedCanvas.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
using System;
using Microsoft.SPOT;
using Microsoft.SPOT.Presentation.Controls;
// using YourApplication; // where the Resources class is

public class AnimatedCanvas : Canvas // You can choose different control instead.
{
private DispatcherTimer _timer;
private int _startID;
private int _endID;
private int _currentID;

private Bitmap _currentBitmap;
private bool _loop;

private int _offsetX;
private int _offsetY;

public AnimatedCanvas()
{
_timer = new DispatcherTimer(Dispatcher);
_timer.Tick += new EventHandler(OnNextFrame);
}

internal AnimatedCanvas(TimeSpan interval, Resources.BitmapResources startBitmap, Resources.BitmapResources endBitmap) : this()
{
_timer.Interval = interval;
_startID = _currentID = (int)startBitmap;
_endID = (int)endBitmap;

if (_startID > _endID)
throw new ArgumentException();

_currentBitmap = Resources.GetBitmap(startBitmap);
}

public TimeSpan Interval { get { return _timer.Interval; } set { _timer.Interval = value; } }

public bool Loop { get { return _loop; } set { _loop = value; } }
public int BackgroundOffsetX { get { return _offsetX; } set { _offsetX = value; } }
public int BackgroundOffsetY { get { return _offsetY; } set { _offsetY = value; } }
public bool IsPlaying { get { return _timer.IsEnabled; } set { _timer.IsEnabled = value; } }

internal Resources.BitmapResources StartBitmap { get { return (Resources.BitmapResources)_startID; } set { _startID = _currentID = (int)value; } }
internal Resources.BitmapResources EndBitmap { get { return (Resources.BitmapResources)_endID; } set { _endID = (int)value; } }

public void Play()
{
_timer.Start();
}

public void Stop()
{
_timer.Stop();
}

public void Rewind()
{
_currentID = _startID;
Invalidate();
}

public override void OnRender(Microsoft.SPOT.Presentation.Media.DrawingContext dc)
{
dc.DrawImage(_currentBitmap, _offsetX, _offsetY);

base.OnRender(dc);
}

protected virtual void OnNextFrame(object sender, EventArgs e)
{
_currentID++;

if (_currentID > _endID)
_currentID = _startID;

else if (_currentID == _endID)
if (!_loop)
_timer.Stop();

_currentBitmap = Resources.GetBitmap((Resources.BitmapResources)_currentID);
Invalidate();
}
}