Mercurial > pub > ImplabNet
annotate Implab.Fx/Animation.cs @ 101:279e226dffdd v2
code cleanup
added EnsureDispatched extension
author | cin |
---|---|
date | Thu, 06 Nov 2014 20:03:19 +0300 |
parents | dfa21d507bc5 |
children |
rev | line source |
---|---|
3 | 1 using System; |
2 using System.Collections.Generic; | |
3 using System.Linq; | |
4 using System.Text; | |
4 | 5 using System.Timers; |
6 using System.ComponentModel; | |
7 using System.Diagnostics; | |
3 | 8 |
9 namespace Implab.Fx | |
10 { | |
4 | 11 public delegate void AnimationStep<T>(T target, int elapsed, int duration); |
12 | |
13 public class Animation<TArg> where TArg: class | |
3 | 14 { |
15 int m_duration; | |
4 | 16 int m_delay; |
17 int m_elapsed; | |
18 int m_prevTicks; | |
19 TArg m_arg; | |
20 ISynchronizeInvoke m_syncronizationObject; | |
21 | |
22 public event AnimationStep<TArg> Step; | |
23 | |
24 Promise<TArg> m_promise; | |
25 | |
26 public Animation(TArg target, int duration, int delay) | |
27 { | |
28 if (duration <= 0) | |
29 throw new ArgumentOutOfRangeException("duration"); | |
30 if (delay <= 0) | |
31 throw new ArgumentOutOfRangeException("delay"); | |
32 | |
33 m_arg = target; | |
34 m_syncronizationObject = target as ISynchronizeInvoke; | |
35 m_duration = duration; | |
36 m_delay = delay; | |
37 m_promise = new Promise<TArg>(); | |
38 } | |
39 | |
40 public Animation(TArg target) | |
41 : this(target, 500, 30) | |
42 { | |
43 } | |
44 | |
45 public TArg Traget | |
46 { | |
47 get { return m_arg; } | |
48 } | |
3 | 49 |
4 | 50 public Promise<TArg> Play() |
51 { | |
52 var timer = new Timer(m_delay); | |
53 | |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
4
diff
changeset
|
54 timer.AutoReset = false; |
4 | 55 timer.SynchronizingObject = m_syncronizationObject; |
56 timer.Elapsed += new ElapsedEventHandler(timer_Elapsed); | |
3 | 57 |
4 | 58 m_prevTicks = Environment.TickCount; |
59 | |
60 timer.Start(); | |
61 | |
62 return m_promise; | |
63 } | |
64 | |
65 void timer_Elapsed(object sender, ElapsedEventArgs args) | |
66 { | |
67 var timer = sender as Timer; | |
68 | |
69 var dt = Environment.TickCount - m_prevTicks; | |
70 m_prevTicks = Environment.TickCount; | |
71 | |
72 m_elapsed += dt; | |
73 | |
74 if (m_elapsed > m_duration) | |
75 m_elapsed = m_duration; | |
76 | |
77 try | |
78 { | |
79 var handler = Step; | |
80 if (handler != null) | |
81 handler(m_arg, m_elapsed, m_duration); | |
82 } | |
83 catch (Exception e) | |
84 { | |
85 Trace.TraceError(e.ToString()); | |
86 } | |
87 | |
88 if (m_elapsed < m_duration) | |
89 timer.Start(); | |
90 else | |
91 { | |
92 timer.Dispose(); | |
93 m_promise.Resolve(m_arg); | |
94 } | |
95 } | |
3 | 96 } |
97 } |