James Montemagno
James Montemagno

Live, Love, Bike, and Code.

Live, Love, Bike, and Code

Share


Tags


James Montemagno

Animate Anything with Xamarin.Forms

I have been building apps with Xamarin.Forms for nearly 6 years now! I love how it has evolved over the years, added new controls, new features, and simplified everything with Shell. While I think I can build pretty decent apps in general, one thing that I have  always struggled with is animations. The very first release of Xamarin.Forms had a built in animation system to fade, move, and scale any of the controls. These are great and there have been several videos on how to use these:

One thing that I always wanted.... was more control! On my Twitch stream a few weeks ago I was trying to spin a little icon that looped when I was submitting a friend request and it was brought to my attention that there is a full animation system built in to do just about anything you want.

To accomplish this, it requires a bit of code in the code behind using the Animation class.

readonly Animation rotation;
        

public SubmitFriendRequestPage()
{
    //..
    rotation = new Animation(v => LabelRotateIcon.Rotation = v, 0, 360);

    VM.PropertyChanged += OnPropertyChanged;
}

Here we create a new custom Animation. It takes in a a callback to set any properties to a value that will be increased over time. The next two parameters are the start and stop values. So here I am saying start playing the animation with the rotation starting at 0 and then stop when you reach 360.

Next, comes time to play the animation, which I do when my IsBusy property changes. The Animation class allows you to name and check an animation at any time, which is very nifty.

void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
    if(e.PropertyName == nameof(VM.IsBusy))
    {
        if (!VM.IsBusy)
            this.AbortAnimation("rotate");
        else
            rotation.Commit(this, "rotate", 16, 1000, Easing.Linear, (v, c) => 			LabelRotateIcon.Rotation = 0, () => true);
    }
}

So, a few things happening here. First is AbortAnimation, which says hey if you are running "rotate" animation stop it. Next is Commit of the animation which will start it. Here I am saying the owner of the animation is the page, the name is "rotate", update very 16 milliseconds, run for 1000 milliseconds, and do linear easing on it. Now, the last two are functions, which are nice touches. The first is what to do when you finish (reset to 0) and then the last function is if you want to loop the animation!

That's it! Literally 3 lines of code to create, start, and stop the custom animation. For some reason I never knew this existed even though there have been a bunch of really cool libraries built on top of is such as Xamanimation.

To learn more about custom animations checkout the full documentation!

Copyright © James Montemagno 2020 All rights reserved. Privacy Policy

View Comments