mercredi 11 mai 2016

How to draw an Arc using a Timer for UWP apps to make it look like a loader (Works for Mobile/Desktop/Xbox) [C#,XAML]

What I wanted to do was to create a circle that draws itself and that looks like its going to load something, and because a picture is better then a 1000 words here is what I mean:



I did not create the files Arc and ArcHelper this gentleman did : https://github.com/arek-kubiak/ArcControl/tree/master

And thus has allowed me to gain some time as I wont need to create an ArcControl I can just use his repo, here is what the initial Arc Control looks like:


What I currently have:

  • a Circle that can drawn using the percentage value. 


What I will need to do:

  • Increase that percentage value to make it look like it is drawing itself 
  • Have an event fired when the circle percentage reach's 100% (so that i can do something with it afterwards)
Here is what my UserControl looks like:


  <arcControl:Arc x:Name="MyArcLoader" 
                   Radius="65" 
                   Fill="White" 
                   PercentValue="1" 
                   Thickness="5" 
                   Margin="10" />

As you can see my PercentValue starts at 1 (it could be 0 also).

Now once our UserControl has loaded all we need to is add a DispatcherTimer set the Interval and increase the Percentage Value by the amount that we want.

For my case, I have set set the Interval to 5 milliseconds and will be increasing the Percentage value by 0.45.  Here is my UserControl:


 public sealed partial class LoadingInUserControl : UserControl
    {
        static DispatcherTimer Timer;
        public event Action OnAutoNextTick;
      
        public LoadingInUserControl()
        {
            this.InitializeComponent();
            Loaded += MainPage_Loaded;
        }

        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            //step up timer
            Timer = new DispatcherTimer();
            Timer.Interval = TimeSpan.FromMilliseconds(5);
            Timer.Tick += Timer_Tick;
            Timer.Start();
        }

        private void Timer_Tick(object sender, object e)
        {
            if (MyArcLoader.PercentValue < 100)
            {
                MyArcLoader.PercentValue = MyArcLoader.PercentValue + .45;
                MyArcLoader.UpdateLayout();
            }
            else
            {
                OnAutoNextTick?.Invoke();
                Dispose();
            }
        }

        public void Dispose()
        {
            if (Timer == null)
            {
                return;
            }
            Timer.Stop();
            Timer.Tick -= Timer_Tick;
            Timer = null;
        }
    }

My OnAutoNextTick action allows me to know when the Arc has hit that 100 percent value outside of the usercontrol.

Add this is what the final control looks like:



If you have an questions don't hesitate to ask!
Happy coding