├── LICENSE ├── README.md ├── ReactiveAnimation.csproj ├── ReactiveAnimation.nuspec ├── linqpad-samples └── Reactive Animation Sample.linq ├── packages.config └── src ├── Animation.cs ├── Easing.cs ├── LinearAnimation.cs ├── ObservableHelper.cs └── Properties └── AssemblyInfo.cs /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Reactive-Animation 2 | Small, simple C# animation library built using the reactive extensions framework, utilizing Robert Penner's easing functions. Does not make use of reflection, instead allowing the caller to use a function/monad/observer to update their desired object. 3 | 4 | Available as a NuGet package at https://www.nuget.org/packages/ReactiveAnimation/ 5 | 6 | ## Why use reactive extensions? 7 | Observables are very useful, because it allows you to easily react to events like resizes or repositions etc. For example, you can animate an object to chase another object that is being animated, and have the animations scale automatically when the Form they are on changes size. 8 | All the hard work is being done on separate threads, so you don't have to worry about it. For Windows Forms, Rx can ensure that your subscribed observer executes on the Control thread, so it's super easy to update properties etc. without worrying about using Invoke. 9 | 10 | ## Principles 11 | - The Animation sets the duration and (optionally) the easing function. 12 | - Then you specify what values you want to animate, which you then subscribe to, essentially registering an observer that will update the desired object. 13 | - Then you start the animation. 14 | - Animations can be paused, cancelled, or skipped to completion etc. 15 | 16 | ## Examples 17 | - Create an Animation that will last for 3 seconds and ease in and out using the quadratic curve 18 | ```cs 19 | var a = new Animation { 20 | DurationInFrames = Animation.FromTimeSpanToDurationInFrames(3), 21 | EasingFunction = ef => Easing.EaseInOut(ef, EasingType.Quadratic) 22 | }; 23 | ``` 24 | - Using this animation, register an observer to animate a float from 0.8 to 1.0 and use the value to set the opacity of a form 25 | ```cs 26 | a.AnimateOnControlThread( 27 | form, 28 | ObservableHelper.FixedValue((float)0.8), 29 | ObservableHelper.FixedValue((float)1), 30 | v => f.Opacity = v.CurrentValue 31 | ); 32 | ``` 33 | - Start the animation 34 | ```cs 35 | a.Start(); 36 | ``` 37 | 38 | - Or, if you want to animate a Windows Form Control without an easing function, and you want a specific speed as opposed to a set duration, you can use the LinearAnimation static class. 39 | ```cs 40 | var cts = LinearAnimation.AnimateControl( 41 | button, // control to animate 42 | ObservableHelper.FixedValue(new Point(0, 150)), // animate until at this position 43 | ObservableHelper.FixedValue(5), // speed to move at 44 | true); // keep in same relative position when the control's parent resizes 45 | // returns a CancellationTokenSource that you can use to cancel the animation 46 | ``` 47 | 48 | [![MyGet Build Status](https://www.myget.org/BuildSource/Badge/progamer-me?identifier=e8f7d0bd-e97a-4f4d-be10-e3d80f613a26)](https://www.myget.org/) 49 | -------------------------------------------------------------------------------- /ReactiveAnimation.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {0516090A-D9A9-41CA-81B1-3EEE60562ACD} 8 | Library 9 | Properties 10 | ReactiveAnimation 11 | ReactiveAnimation 12 | v4.5 13 | 512 14 | 15 | 16 | true 17 | full 18 | false 19 | bin\Debug\ 20 | DEBUG;TRACE 21 | prompt 22 | 4 23 | bin\Debug\ReactiveAnimation.XML 24 | 25 | 26 | pdbonly 27 | true 28 | bin\Release\ 29 | TRACE 30 | prompt 31 | 4 32 | bin\Release\ReactiveAnimation.XML 33 | 34 | 35 | 36 | 37 | 38 | 39 | packages\Rx-Core.2.2.5\lib\net45\System.Reactive.Core.dll 40 | 41 | 42 | packages\Rx-Interfaces.2.2.5\lib\net45\System.Reactive.Interfaces.dll 43 | 44 | 45 | packages\Rx-Linq.2.2.5\lib\net45\System.Reactive.Linq.dll 46 | 47 | 48 | packages\Rx-PlatformServices.2.2.5\lib\net45\System.Reactive.PlatformServices.dll 49 | 50 | 51 | packages\Rx-WinForms.2.2.5\lib\net45\System.Reactive.Windows.Forms.dll 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 76 | 77 | -------------------------------------------------------------------------------- /ReactiveAnimation.nuspec: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ReactiveAnimation 5 | $version$ 6 | Reactive Animation 7 | $author$ 8 | $author$ 9 | https://github.com/keith-hall/reactive-animation/blob/master/LICENSE 10 | https://github.com/keith-hall/reactive-animation 11 | false 12 | Small, simple open-source C# animation library built using the reactive extensions framework, utilizing Robert Penner's easing functions. Does not make use of reflection, instead allowing the caller to use a function/monad/observer to update their desired object. 13 | Contains methods for animating Windows Forms Controls. 14 | 15 | Includes a LINQPad sample. 16 | C# animation library built using the reactive extensions framework 17 | 18 | en-GB 19 | animation tween linqpad-samples Reactive Rx LINQ Observable Events 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /linqpad-samples/Reactive Animation Sample.linq: -------------------------------------------------------------------------------- 1 | 2 | Rx-Main 3 | Rx-WinForms 4 | System.Reactive.Linq 5 | System.Reactive.Subjects 6 | System.Threading.Tasks 7 | System.Windows.Forms 8 | System.Drawing 9 | System.Reactive.Concurrency 10 | System.Reactive 11 | ReactiveAnimation 12 | 13 | void Main() // LINQPad sample 14 | { 15 | var a = new Animation { DurationInFrames = Animation.FromTimeSpanToDurationInFrames(3), EasingFunction = ef => Easing.EaseInOut(ef, EasingType.Quadratic) }; 16 | var f = new Form { Width = 600, Height = 500 }; 17 | var b = new Button { Text = "Hello", Width = 100, Height = 50, Top = 50, Visible = true }; 18 | var b2 = new Button { Text = "World", Width = 100, Height = 50, Top = 400, Visible = true }; 19 | f.Controls.Add(b); 20 | f.Controls.Add(b2); 21 | f.Show(); 22 | f.Update(); 23 | f.Refresh(); 24 | f.Focus(); 25 | f.FormClosing += (o, ev) => { a.Dispose(); Environment.Exit(0); }; 26 | 27 | var newPosForB = ObservableHelper.PositionBasedOnParent(b, c => new Rectangle(c.Parent.ClientSize.Width - c.Width, c.Top, c.Width, c.Height)); 28 | var newPosForB2 = ObservableHelper.PositionBasedOnControl(b, c => new Rectangle(c.Left, c.Top + c.Height, b2.Width, b2.Height)); 29 | //newPosForB.DumpLatest(true); // commented out due to LINQPad not focusing the form when there are dumped objects 30 | //newPosForB2.Dump(); 31 | a.AnimateControlPosition(b, ObservableHelper.FixedValue(b.Bounds), newPosForB); 32 | a.AnimateControlPosition(b2, ObservableHelper.FixedPositionRelativeToParent(b2).Select(p => new Rectangle(p.X, p.Y, b2.Width, b2.Height)), newPosForB2); 33 | 34 | a.AnimateOnControlThread(f, ObservableHelper.FixedValue((float)0.8), ObservableHelper.FixedValue((float)1), v => f.Opacity = v.CurrentValue); 35 | 36 | a.Progress.Subscribe(v => {}, () => { 37 | b.Invoke(() => { 38 | b.Text = "Complete!"; 39 | var ct = new CancellationTokenSource(); 40 | newPosForB.Subscribe(b.SetBounds, ct.Token); 41 | newPosForB2.Subscribe(b2.SetBounds, ct.Token); 42 | b.Disposed += (o, ef) => ct.Cancel(); 43 | }); 44 | }); 45 | a.Start(); 46 | 47 | new Task(() => { 48 | Thread.Sleep(1500); 49 | b2.Invoke(() => b2.Text = "Paused..."); 50 | a.Pause(); 51 | //f.Invoke(() => f.Width = (int)((double)f.Width * 1.5)); 52 | //f.Invoke(() => f.WindowState = FormWindowState.Maximized); // resize the form to show the animation is also updated 53 | Thread.Sleep(1000); 54 | b2.Invoke(() => b2.Text = "World"); 55 | a.Start(); 56 | }).Start(); 57 | 58 | b2.Click += (o, e) => { 59 | var a2 = new Animation { DurationInFrames = Animation.FromTimeSpanToDurationInFrames(0.2), EasingFunction = v => Easing.EaseOut(v, EasingType.Sine) }; 60 | // showing a different way of doing it 61 | a2.CreateObservable(ObservableHelper.FixedValue((float)f.Width), ObservableHelper.FixedValue((float)f.Width * (float)1.2)).ObserveOn(f).Subscribe(v => f.Width = (int)v.First().CurrentValue); 62 | a2.Start(); 63 | }; 64 | b.Click += (o, e) => { 65 | var a2 = new Animation { DurationInFrames = Animation.FromTimeSpanToDurationInFrames(1), EasingFunction = v => Easing.EaseOut(v, EasingType.Linear) }; 66 | var d1 = new Dictionary(); 67 | d1.Add("R", 127); 68 | d1.Add("G", 255); 69 | d1.Add("B", -255); 70 | var d2 = new Dictionary(); 71 | d2.Add("R", 0); 72 | d2.Add("G", -127); 73 | d2.Add("B", 255); 74 | 75 | a2.AnimateOnControlThread(b, a2.CreateObservable(ObservableHelper.FixedValue(d1), ObservableHelper.FixedValue(d2))/*.Dump()*/, eap => b.BackColor = Color.FromArgb((int)Math.Abs(eap.Single (p => p.Key == "R").CurrentValue), (int)Math.Abs(eap.Single (p => p.Key == "G").CurrentValue), (int)Math.Abs(eap.Single (p => p.Key == "B").CurrentValue)), () => b.ForeColor = Color.White); 76 | a2.Start(); 77 | }; 78 | } 79 | 80 | public static class ControlExtensions { 81 | public static void Invoke (this Control control, Action action) { 82 | control.Invoke(action); 83 | } 84 | 85 | public static void SetBounds (this Control control, Rectangle newBounds) { 86 | control.SetBounds(newBounds.Left, newBounds.Top, newBounds.Width, newBounds.Height); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /packages.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /src/Animation.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | //using System.Reactive; 5 | using System.Reactive.Linq; 6 | using System.Reactive.Subjects; 7 | using System.Threading; 8 | using System.Windows.Forms; 9 | using System.Drawing; 10 | using AnimatableValue = System.Collections.Generic.KeyValuePair; 11 | 12 | namespace ReactiveAnimation 13 | { 14 | /// 15 | /// Used to create a new animation, with a set duration and specific easing function, that can then be used to tween multiple properties. 16 | /// 17 | public class Animation : IDisposable 18 | { 19 | public const int FrameRate = 60; 20 | 21 | /// 22 | /// An observable that pulses on every frame. 23 | /// 24 | public static readonly IObservable EveryFrame = Observable.Interval(TimeSpan.FromMilliseconds((double)1000 / (double)FrameRate)) // create a cold observable 25 | .Publish().RefCount(); // only pulse while subscribers are connected 26 | /// 27 | /// Convert the given to a duration in frames, based on the framerate. 28 | /// 29 | /// The duration to convert to frames. 30 | /// The number of frames in the specified . 31 | public static int FromTimeSpanToDurationInFrames(TimeSpan timespan) 32 | { 33 | return FromTimeSpanToDurationInFrames(timespan.TotalSeconds); 34 | } 35 | 36 | /// 37 | /// Convert the given number of to a duration in frames, based on the framerate. 38 | /// 39 | /// The duration to convert to frames. 40 | /// The number of frames in the specified . 41 | public static int FromTimeSpanToDurationInFrames(double seconds) 42 | { 43 | return (int)(seconds * FrameRate); 44 | } 45 | 46 | 47 | internal int _elapsedFrames = 0; 48 | private int _durationInFrames = FrameRate; // default to a duration of 1 second 49 | private bool _alreadyDisposed = false; 50 | 51 | public int DurationInFrames 52 | { 53 | get 54 | { 55 | return _durationInFrames; 56 | } 57 | set 58 | { 59 | CheckNotDisposed(); 60 | if (value < 1) 61 | throw new ArgumentOutOfRangeException(nameof(DurationInFrames), "Duration cannot be less than one frame"); 62 | else if (value < _elapsedFrames) 63 | throw new ArgumentOutOfRangeException(nameof(DurationInFrames), "Duration cannot be less than elapsed frames. If you want a shorter duration, you will need to restart the animation."); 64 | else 65 | _durationInFrames = value; 66 | } 67 | } 68 | 69 | internal Subject _progress; 70 | 71 | /// 72 | /// An observable that pulses on every frame while the animation is running, with the eased percentage completion of the animation. 73 | /// 74 | public IObservable Progress 75 | { 76 | get 77 | { 78 | CheckNotDisposed(); 79 | return _progress.AsObservable(); // best to hide the identity of a subject, because we don't need to expose state information 80 | } 81 | } 82 | public Func EasingFunction { get; set; } 83 | internal CancellationTokenSource _cancelProgress; 84 | //x internal List _cancelChildren; 85 | 86 | public bool IsRunning 87 | { 88 | get 89 | { 90 | CheckNotDisposed(); 91 | return _cancelProgress != null && !_cancelProgress.IsCancellationRequested; 92 | } 93 | } 94 | 95 | public Animation() 96 | { 97 | _progress = new Subject(); 98 | //x _cancelChildren = new List(); 99 | Pause(); 100 | } 101 | 102 | public void Start() 103 | { 104 | Pause(); // ensure the animation is not running 105 | _cancelProgress = new CancellationTokenSource(); // create a new cancellation token source, so we can pause or complete the animation 106 | 107 | if (EasingFunction == null) // if there is no easing function specified, use the default linear type 108 | EasingFunction = (progress) => Easing.EaseInOut(progress, EasingType.Linear); 109 | 110 | try 111 | { 112 | EveryFrame.Subscribe(onNext => 113 | { 114 | if (_elapsedFrames == DurationInFrames) 115 | { // if the animation is complete, cancel it to break out of this subscription to EveryFrame 116 | //? NOTE: we actually do this on the next frame to ensure the subscribers have had time to process the completion... maybe this is a HACK: ? 117 | Pause(); 118 | Dispose(true); 119 | return; 120 | } 121 | _cancelProgress.Token.ThrowIfCancellationRequested(); 122 | 123 | _elapsedFrames++; 124 | 125 | UpdateProgress(); 126 | }, 127 | //x onError => onError.Dump("Animation Start -> onError"), 128 | _cancelProgress.Token); 129 | } 130 | catch (InvalidOperationException ex) 131 | { 132 | // Invoke or BeginInvoke cannot be called on a control until the window handle has been created. [Source = Pooled Thread] 133 | // TODO: better to get subscribers to unsubscribe when form is being closed? 134 | //ex.Dump("Animation Start -> Caught error"); 135 | //CleanUp(); 136 | } 137 | } 138 | 139 | internal void UpdateProgress() 140 | { 141 | var percentComplete = (double)_elapsedFrames / (double)DurationInFrames; // determine the percent complete of the animation 142 | _progress.OnNext(EasingFunction(percentComplete)); // apply the easing function to the progress percentage, and report the eased value to any subscribers 143 | 144 | if (_elapsedFrames == DurationInFrames) 145 | _progress.OnCompleted(); // report the completion of this animation to any subscribers 146 | } 147 | 148 | public void Pause() 149 | { 150 | CheckNotDisposed(); 151 | if (_cancelProgress != null) 152 | _cancelProgress.Cancel(); 153 | } 154 | 155 | public void Restart() 156 | { 157 | Pause(); 158 | GoToSpecificFrame(0); 159 | Start(); 160 | } 161 | 162 | public void GoToSpecificFrame(int frameNumber) 163 | { 164 | CheckNotDisposed(); 165 | if (frameNumber < 0 || frameNumber > DurationInFrames) 166 | throw new ArgumentOutOfRangeException(nameof(frameNumber)); 167 | //? TODO: enforce that the animation is paused first? else may have threading issues whereby the elapsed frames is greater than the duration? 168 | 169 | _elapsedFrames = frameNumber; 170 | UpdateProgress(); 171 | } 172 | 173 | public void SkipToCompletion() 174 | { 175 | Pause(); 176 | GoToSpecificFrame(DurationInFrames); 177 | } 178 | 179 | /// 180 | /// Contains useful information about the progress of specific values in the animation. 181 | /// 182 | public struct AnimationProgress 183 | { 184 | public string Key { get; internal set; } 185 | public float Progress { get; internal set; } 186 | public float FromValue { get; internal set; } 187 | public float ToValue { get; internal set; } 188 | 189 | public float CurrentValue 190 | { 191 | get 192 | { 193 | return FromValue + (ToValue - FromValue) * Progress; 194 | } 195 | } 196 | } 197 | 198 | /// 199 | /// create an observable for animating multiple related values at once 200 | /// 201 | /// the observable values to animate from 202 | /// the observable values to animate to 203 | /// observable animation progress for subscription and updating the target object 204 | public IObservable> CreateObservable(IObservable> fromValues, IObservable> toValues) 205 | { 206 | return Progress.CombineLatest(fromValues.DistinctUntilChanged(), toValues.DistinctUntilChanged(), 207 | (p, f, t) => f.Join(t, fv => fv.Key, tv => tv.Key, 208 | (fv, tv) => new AnimationProgress 209 | { 210 | Key = fv.Key, 211 | FromValue = fv.Value, 212 | ToValue = tv.Value, 213 | Progress = p 214 | })); 215 | } 216 | 217 | 218 | /// 219 | /// create an observable for animating a single value 220 | /// 221 | /// the observable value to animate from 222 | /// the observable value to animate to 223 | /// the name you want to assign the value 224 | /// observable animation progress for subscription and updating the target object 225 | public IObservable> CreateObservable(IObservable fromValue, IObservable toValue, string valueName = "Value") 226 | { 227 | Func> conv = f => Enumerable.Repeat(new AnimatableValue(valueName, f), 1); 228 | return CreateObservable(fromValue.Select(conv), toValue.Select(conv)); 229 | } 230 | 231 | /*// commented out because subscription automatically ends upon completion 232 | /// 233 | /// subscribe to an observable, and cancel the subscription automatically when the animation completes 234 | /// 235 | /// the observable animation to subscribe to 236 | /// the action to perform on each frame 237 | /// a cancellation token, so that it can be cancelled separately from other animations controlled by this Animation 238 | internal CancellationTokenSource SubscribeDuringAnimation (IObservable> animation, Action> onNext) 239 | { 240 | var cts = new CancellationTokenSource(); 241 | _cancelChildren.Add(cts); 242 | 243 | animation.Subscribe(onNext, cts.Token); 244 | 245 | return cts; 246 | }*/ 247 | 248 | public static IEnumerable ConvertRectangleToEnumerable(Rectangle rect) 249 | { 250 | Func kvp = (s, i) => new AnimatableValue(s, i); 251 | 252 | return new[] 253 | { 254 | kvp("Left", rect.Left), 255 | kvp("Top", rect.Top), 256 | kvp("Width", rect.Width), 257 | kvp("Height", rect.Height) 258 | }; 259 | } 260 | 261 | public static Rectangle ConvertEnumerableToRectangle(IEnumerable rectEnumerable) 262 | { 263 | var coords = rectEnumerable.ToArray(); 264 | 265 | //x return new Rectangle((int)coords[0].CurrentValue, (int)coords[1].CurrentValue, (int)coords[2].CurrentValue, (int)coords[3].CurrentValue); 266 | return new Rectangle((int)coords.Single(ap => ap.Key == "Left").CurrentValue, (int)coords.Single(ap => ap.Key == "Top").CurrentValue, (int)coords.Single(ap => ap.Key == "Width").CurrentValue, (int)coords.Single(ap => ap.Key == "Height").CurrentValue); 267 | } 268 | 269 | /// 270 | /// animate a Windows Forms Control, automatically subscribing and observing on the control's thread 271 | /// 272 | /// the Windows Forms Control to animate 273 | /// the starting position 274 | /// the ending position 275 | /// an action to run on completion of the animation 276 | public void AnimateControlPosition(Control ctrl, IObservable fromPosition, IObservable toPosition, Action onCompletion = null) 277 | { 278 | AnimateOnControlThread(ctrl, CreateObservable(fromPosition.Select(ConvertRectangleToEnumerable), toPosition.Select(ConvertRectangleToEnumerable)), eap => UpdateControlPosition(ctrl, ConvertEnumerableToRectangle(eap)), onCompletion); 279 | } 280 | 281 | // static 282 | public void AnimateOnControlThread(Control ctrl, IObservable> animationObservable, Action> onNext, Action onCompletion = null) 283 | { 284 | Action completion = () => 285 | { 286 | if (onCompletion != null) 287 | ctrl.Invoke(onCompletion); 288 | }; 289 | animationObservable 290 | .ObserveOn(ctrl) 291 | .Subscribe(onNext, completion); 292 | } 293 | 294 | public void AnimateOnControlThread(Control ctrl, IObservable fromValue, IObservable toValue, Action onNext, Action onCompletion = null) 295 | { 296 | AnimateOnControlThread(ctrl, CreateObservable(fromValue, toValue), eap => onNext(eap.First()), onCompletion); 297 | } 298 | 299 | public static void UpdateControlPosition(Control ctrl, Rectangle newPosition) 300 | { 301 | ctrl.SetBounds(newPosition.Left, newPosition.Top, newPosition.Width, newPosition.Height); 302 | ctrl.Parent.Refresh(); 303 | } 304 | 305 | public void Dispose() 306 | { 307 | Dispose(true); 308 | GC.SuppressFinalize(this); 309 | } 310 | 311 | protected virtual void Dispose(bool isDisposing) 312 | { 313 | // Don't dispose more than once. 314 | if (_alreadyDisposed) 315 | return; 316 | if (isDisposing) 317 | { 318 | // free managed resources 319 | Pause(); 320 | //x foreach (var cts in _cancelChildren) 321 | //x cts.Cancel(); 322 | _progress.Dispose(); 323 | } 324 | // free unmanaged resources 325 | 326 | _alreadyDisposed = true; 327 | } 328 | 329 | protected void CheckNotDisposed() 330 | { 331 | if (_alreadyDisposed) 332 | throw new ObjectDisposedException(this.GetType().Name); 333 | } 334 | } 335 | } 336 | -------------------------------------------------------------------------------- /src/Easing.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace ReactiveAnimation 4 | { 5 | public static class Easing 6 | { 7 | // Adapted from source : http://www.robertpenner.com/easing/ 8 | 9 | public static float Ease(double linearStep, float acceleration, EasingType type) 10 | { 11 | float easedStep = acceleration > 0 ? EaseIn(linearStep, type) : 12 | acceleration < 0 ? EaseOut(linearStep, type) : 13 | (float)linearStep; 14 | 15 | return MathHelper.Lerp(linearStep, easedStep, Math.Abs(acceleration)); 16 | } 17 | 18 | public static float EaseIn(double linearStep, EasingType type) 19 | { 20 | switch (type) 21 | { 22 | case EasingType.Linear: return (float)linearStep; 23 | case EasingType.Sine: return Sine.EaseIn(linearStep); 24 | case EasingType.Quadratic: //return Power.EaseIn(linearStep, 2); 25 | case EasingType.Cubic: //return Power.EaseIn(linearStep, 3); 26 | case EasingType.Quartic: //return Power.EaseIn(linearStep, 4); 27 | case EasingType.Quintic: return Power.EaseIn(linearStep, (int)type); 28 | } 29 | throw new NotImplementedException(); 30 | } 31 | 32 | public static float EaseOut(double linearStep, EasingType type) 33 | { 34 | switch (type) 35 | { 36 | case EasingType.Linear: return (float)linearStep; 37 | case EasingType.Sine: return Sine.EaseOut(linearStep); 38 | case EasingType.Quadratic: //return Power.EaseOut(linearStep, 2); 39 | case EasingType.Cubic: //return Power.EaseOut(linearStep, 3); 40 | case EasingType.Quartic: //return Power.EaseOut(linearStep, 4); 41 | case EasingType.Quintic: return Power.EaseOut(linearStep, (int)type); 42 | } 43 | throw new NotImplementedException(); 44 | } 45 | 46 | public static float EaseInOut(double linearStep, EasingType easeInType, EasingType easeOutType) 47 | { 48 | return linearStep < 0.5 ? EaseInOut(linearStep, easeInType) : EaseInOut(linearStep, easeOutType); 49 | } 50 | public static float EaseInOut(double linearStep, EasingType type) 51 | { 52 | switch (type) 53 | { 54 | case EasingType.Linear: return (float)linearStep; 55 | case EasingType.Sine: return Sine.EaseInOut(linearStep); 56 | case EasingType.Quadratic: //return Power.EaseInOut(linearStep, 2); 57 | case EasingType.Cubic: //return Power.EaseInOut(linearStep, 3); 58 | case EasingType.Quartic: //return Power.EaseInOut(linearStep, 4); 59 | case EasingType.Quintic: return Power.EaseInOut(linearStep, (int)type); 60 | } 61 | throw new NotImplementedException(); 62 | } 63 | 64 | static class Sine 65 | { 66 | public static float EaseIn(double s) 67 | { 68 | return (float)Math.Sin(s * MathHelper.HalfPi - MathHelper.HalfPi) + 1; 69 | } 70 | public static float EaseOut(double s) 71 | { 72 | return (float)Math.Sin(s * MathHelper.HalfPi); 73 | } 74 | public static float EaseInOut(double s) 75 | { 76 | return (float)(Math.Sin(s * MathHelper.Pi - MathHelper.HalfPi) + 1) / 2; 77 | } 78 | } 79 | 80 | static class Power 81 | { 82 | public static float EaseIn(double s, int power) 83 | { 84 | return (float)Math.Pow(s, power); 85 | } 86 | public static float EaseOut(double s, int power) 87 | { 88 | var sign = power % 2 == 0 ? -1 : 1; 89 | return (float)(sign * (Math.Pow(s - 1, power) + sign)); 90 | } 91 | public static float EaseInOut(double s, int power) 92 | { 93 | s *= 2; 94 | if (s < 1) return EaseIn(s, power) / 2; 95 | var sign = power % 2 == 0 ? -1 : 1; 96 | return (float)(sign / 2.0 * (Math.Pow(s - 2, power) + sign * 2)); 97 | } 98 | } 99 | } 100 | 101 | public enum EasingType 102 | { 103 | Linear, 104 | Sine, 105 | Quadratic = 2, 106 | Cubic = 3, 107 | Quartic = 4, 108 | Quintic = 5 109 | } 110 | 111 | public static class MathHelper 112 | { 113 | public const float Pi = (float)Math.PI; 114 | public const float HalfPi = (float)(Math.PI / 2); 115 | 116 | public static float Lerp(double from, double to, double step) 117 | { 118 | return (float)((to - from) * step + from); 119 | } 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /src/LinearAnimation.cs: -------------------------------------------------------------------------------- 1 | using System.Drawing; 2 | using System.Windows.Forms; 3 | using System.Reactive.Linq; 4 | using System.Threading; 5 | using System; 6 | 7 | namespace ReactiveAnimation { 8 | /// 9 | /// This static class is designed to help with linear animation - i.e. with no easing function, 10 | /// when you want an animation with a set speed rather than a set duration. 11 | /// 12 | public static class LinearAnimation { 13 | public struct Position { 14 | public T ObjectToAnimate; 15 | public Point NewPosition; 16 | public Point DesiredPosition; 17 | } 18 | 19 | public static int GetPositionOneStepCloserToDestination (int currentPos, int targetPos, int speed) { 20 | speed = Math.Abs(speed); 21 | if (currentPos == targetPos) // if it is already at the desired position 22 | return targetPos; // return it 23 | var distance = currentPos - targetPos; // determine the distance between the current position and the desired position 24 | if (Math.Abs(distance) < speed) // if it is less than the speed 25 | return targetPos; // return the desired position 26 | return currentPos + ((currentPos > targetPos) ? -speed : speed); // return the value after the speed (towards the desired position) has been applied 27 | } 28 | 29 | private static Position GetNewPosition (T objectToAnimate, Func currentPosition, Point desiredPosition, int speed) { 30 | var c = currentPosition(objectToAnimate); 31 | var p = new Position { 32 | ObjectToAnimate = objectToAnimate, 33 | DesiredPosition = desiredPosition, 34 | NewPosition = new Point(GetPositionOneStepCloserToDestination(c.X, desiredPosition.X, speed), GetPositionOneStepCloserToDestination(c.Y, desiredPosition.Y, speed)) 35 | }; 36 | return p; 37 | } 38 | 39 | public static IObservable> CreateObservable (T objectToAnimate, Func currentPosition, IObservable toPosition, IObservable speed) { 40 | return Animation.EveryFrame.CombineLatest(toPosition, speed, (f, p, s) => new { f, p, s }).DistinctUntilChanged(v => v.f).Select(v => GetNewPosition(objectToAnimate, currentPosition, v.p, v.s)); 41 | } 42 | 43 | public static CancellationTokenSource AnimateControl (Control ctrl, IObservable toPosition, IObservable speed, bool keepRelativePosition) { 44 | var cts = new CancellationTokenSource(); 45 | if (keepRelativePosition) 46 | KeepRelativePosition(ctrl, toPosition, cts); 47 | var move = CreateObservable(ctrl, c => ctrl.Location, toPosition, speed); 48 | move.ObserveOn(ctrl).Subscribe(np => { 49 | np.ObjectToAnimate.Location = np.NewPosition; 50 | if (np.DesiredPosition == np.NewPosition) 51 | cts.Cancel(); 52 | }, cts.Token); 53 | return cts; 54 | } 55 | 56 | public static CancellationTokenSource KeepRelativePosition (Control ctrl, IObservable relativeTo, CancellationTokenSource cts = null) { 57 | Func getRelativePosition = (current, previousFinal, newFinal) => { if (previousFinal == 0) return current; double perc = (double)current / (double)previousFinal; return (int)((double)newFinal * perc); }; 58 | if (cts == null) 59 | cts = new CancellationTokenSource(); 60 | 61 | ObservableHelper.ObserveWithPrevious( 62 | relativeTo.DistinctUntilChanged(), 63 | (prev, current) => new { prev, current }) 64 | .Skip(1) // ignore first value where there is no previous 65 | .ObserveOn(ctrl).Subscribe(v => { 66 | if (v.prev != v.current) { 67 | 68 | var pos = new Point( 69 | getRelativePosition(ctrl.Left, v.prev.X, v.current.X), 70 | getRelativePosition(ctrl.Top , v.prev.Y, v.current.Y) 71 | ); 72 | if (pos != ctrl.Location) { 73 | ctrl.Location = pos; 74 | ctrl.Parent.Refresh(); 75 | } 76 | } 77 | }, cts.Token); 78 | return cts; 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/ObservableHelper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Drawing; 3 | using System.Linq; 4 | using System.Reactive; 5 | using System.Reactive.Linq; 6 | using System.Windows.Forms; 7 | 8 | namespace ReactiveAnimation 9 | { 10 | public static class ObservableHelper 11 | { 12 | private static IObservable PositionBasedOnControl(IObservable> events, Control ctrl, Func getNewPosition) 13 | { 14 | return Observable.Defer(() => FixedValue(getNewPosition(ctrl))).Concat(events.Select(e => getNewPosition(ctrl)).ObserveOn(ctrl)); 15 | } 16 | 17 | /// 18 | /// Get an observable that will update using the provided function when the specified control's position changes. 19 | /// 20 | /// The control to observe. 21 | /// An observable with the position relative to . 22 | public static IObservable PositionBasedOnControl(Control ctrlDestination, Func getNewPosition) 23 | { 24 | return PositionBasedOnControl(Observable.FromEventPattern(ev => ctrlDestination.Move += ev, ev => { if (ctrlDestination != null && !ctrlDestination.IsDisposed) ctrlDestination.Move -= ev; }), ctrlDestination, getNewPosition); 25 | } 26 | 27 | /// 28 | /// Get an observable that will update using the provided function when the specified control's parent's size changes. 29 | /// 30 | /// The control whose parent to observe for size changes. 31 | /// An observable with the position relative to the size of 's parent. 32 | public static IObservable PositionBasedOnParent(Control ctrl, Func getNewPosition) 33 | { 34 | return PositionBasedOnControl(Observable.FromEventPattern(ev => ctrl.Parent.ClientSizeChanged += ev, ev => { if (ctrl != null && !ctrl.IsDisposed) ctrl.Parent.ClientSizeChanged -= ev; }), ctrl, getNewPosition); 35 | } 36 | 37 | /// 38 | /// Convert a value to an observable that will never change. 39 | /// 40 | /// The fixed value. 41 | /// An observable with the constant value specified. 42 | public static IObservable FixedValue(T constantValue) 43 | { 44 | return Enumerable.Repeat(constantValue, 1).ToObservable(); 45 | } 46 | 47 | /// 48 | /// Get an observable Point that will contain a control's position relative to it's parent. 49 | /// 50 | /// The control. 51 | /// An observable with the position relative to the control's parent. 52 | public static IObservable FixedPositionRelativeToParent(Control ctrl) 53 | { 54 | var ps = ctrl.Parent.ClientSize; 55 | var originalXPerc = (float)ctrl.Left / (float)ps.Width; 56 | var originalYPerc = (float)ctrl.Top / (float)ps.Height; 57 | return PositionBasedOnParent(ctrl, c => new Point((int)((float)c.Parent.ClientSize.Width * originalXPerc), (int)((float)c.Parent.ClientSize.Height * originalYPerc))); 58 | } 59 | 60 | /// 61 | /// Get an observable coupled with it's previous value. 62 | /// 63 | /// The source observable. 64 | /// The projection to apply to get the output. 65 | /// An observable coupled with it's previous value. 66 | public static IObservable ObserveWithPrevious (IObservable source, Func projection) { 67 | return source.Scan(Tuple.Create(default(TSource), default(TSource)), 68 | (previous, current) => Tuple.Create(previous.Item2, current)) 69 | .Select(t => projection(t.Item1, t.Item2)); 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("ReactiveAnimation")] 9 | [assembly: AssemblyDescription("Simple Animation framework built on Reactive Extensions")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("Keith Hall")] 12 | [assembly: AssemblyProduct("ReactiveAnimation")] 13 | [assembly: AssemblyCopyright("Copyright © 2015")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("ead15993-b604-461c-9897-9ff19feb1041")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | [assembly: System.CLSCompliant(true)] 38 | --------------------------------------------------------------------------------