Custom Animations in Xamarin Forms

Animations are a great way to show more information on screen and provide a much improved UX. Xamarin Forms has a few animation techniques and I will show how to create a button (or label) that shows that it is progressing and whether it succeeds or fails.

StatusBar

Cross platform custom animations can be done via 2 methods in Xamarin Forms.

  1. Create an Animation object and Commit() it to start.
  2. Use extension methods such as FadeTo and TranslateTo on an IAnimatableObject.

I will explain these further in the article but the extension methods are really just wrappers around an animation object. Extension methods provide a quick way, defining the Animation object yourself gives you greater control of the animation.

Animations are nothing further than a timer (tweener) repeating and changing the property of an object over time until the timer finishes. For example each timer tick updates the width property of an object.

Custom Control

Initially we want to create a custom control to house together the progress bar and label together.

Different Ways To Animate

First I wanted to show that there are 2 ways of animating an IAnimatable object. An IAnimatable object is anything that inherits from VisualElement. You can use a the Xamarin.Forms.ViewExtensions such as

  • FadeTo
  • LayoutTo
  • RelRotateTo
  • RelScaleTo
  • RotateTo
  • RotateXTo
  • RotateYTo
  • ScaleTo
  • TranslateTo

E.g. Just code myAnimatableObject.FadeTo() and animation is as easy at that. To cancel the animation you will need to call ViewExtensions.CancelAnimation(myAnimatableObject); and it will cancel all animations running on it.

If you need a more complex animation you will want to create an Animation object and apply it to the property of the object you want to animate, which I will show below.

Create Animation

To start the progress bar animation going we first need to create an animation to start the label expanding.

The animation accepts a callback that will give the updated value to the property you give it on each cycle. In the example above I am changing the Width. Once we have the animation we need to do a Commit() to start it.

Once started you can only cancel this animation by going on your IAnimatable object .AbortAnimation(“AnimationName”); This is different than CancelAnimations above.

Animations also provide a Finished Callback to run anything after the animation, for example my fading animation.

A full example can be found at: https://github.com/exrin/Tesla-Mobile-App/blob/master/Tesla/Tesla/Tesla/Control/StatusBarLabel.xaml.cs


Posted

in

by

Tags: