Animations in Xamarin and Xamarin.Forms

Sometimes we can use small effects and animations to make the load process or heavy operations look more fluid and fast. This article shows how to add animations to our Xamarin and Xamarin.Forms (iOS, Android and Windows Phone) apps.

There are two possible approaches to do this, the Xamarin way and the Xamarin.Forms approach. Let's start!

Xamarin.Forms

In Xamarin.Forms, every control you can use to build your user interface is based on the View class.

There are some extension methods for this class that allow you, using C# code, to create little animations for your controls. For example, you can create a simple page like this: 
  1. public MainPage()  
  2. {  
  3.     sampleLabel = new Label   
  4.     {   
  5.         Text = "Hello Xamarin.Forms animations!",  
  6.         TextColor = Color.Blue,    
  7.         XAlign = TextAlignment.Center,   
  8.         Opacity = 0   
  9.     };  
  10.   
  11.     Content = new StackLayout  
  12.     {  
  13.         VerticalOptions = LayoutOptions.Center,  
  14.         Children =   
  15.         {  
  16.             sampleLabel  
  17.         }  
  18.     };  
  19. }  
By default, in the code above, the label opacity is set to 0, so it isn't displayed on screen when the page is showed.

Next, you can override the OnAppearing method that is launched just before the page is showed. In this method you can animate the previously created label to make a FadeIn effect:
  1. protected override void OnAppearing()  
  2. {  
  3.     base.OnAppearing();  
  4.   
  5.     sampleLabel.FadeTo(1, 750, Easing.Linear);  
  6. }  
The FadeTo extension method receives the following three parameters:
  • Final value of the property, in this case Opacity

  • Animation duration in milliseconds.

  • Easing function to use. In this case a linear one, meaning a linear acceleration is added to the effect.
There are many more extension methods: ScaleTo, RotateToLayoutTo and TranslateTo, all of them work the same way. You need to provide the final value and the duration, then you can provide an Easing function. You can take a detailed look at them here.

There is also another method in the ViewExtensions class, called CancelAnimation, that get a View as a parameter and allows you to cancel an initiated animation on the target View.

You can also create combined animations, so you show more complex effects on the screen. All methods for animations are async, so you can play with await or not await them to make async or sync animations in an easy way:
  1. protected override async void OnAppearing()  
  2. {  
  3.     base.OnAppearing();  
  4.   
  5.     sampleLabel.FadeTo(1, 750, Easing.Linear);  
  6.   
  7.     await sampleLabel.ScaleTo(2, 1500, Easing.CubicInOut);  
  8.     await sampleLabel.ScaleTo(1, 500, Easing.Linear);  
  9. }  
Here you can see some combined effects:
  • FadeTo, with a duration of 750 milliseconds, without await.

  • ScaleTo, with a duration of 1500 milliseconds, with await. This one is launched at the same time of the FadeTo, since it is not awaited.

  • ScaleTo, with a duration of 500 milliseconds, with await. Since the previous ScaleTo is awaited, this one is launched when the previous one finished. 
This way gives you a big control over how the animations are launched and allows you to combine many little animations to do awesome things.

Xamarin

Now we will see how to make the same animation in Xamarin. Since Xamarin asks you to create a native view for each platform, you will need to know how to make animations in iOS, Android and Windows.

Windows

In Windows  and Windows Phone you can use the power of XAML to create awesome animations. In the first place let's start creating the same Label, a TextBlock in XAML:
  1. <Grid>  
  2.     <TextBlock x:Name="TextHello"   
  3.                 Text="{Binding Hello}"  
  4.                 VerticalAlignment="Center"  
  5.                 HorizontalAlignment="Center"  
  6.                 Foreground="Blue"  
  7.                 Opacity="0"  
  8.                 RenderTransformOrigin=".5,.5">  
  9.         <TextBlock.RenderTransform>  
  10.             <CompositeTransform ScaleX="1" ScaleY="1"/>  
  11.         </TextBlock.RenderTransform>  
  12.     </TextBlock>  
  13. </Grid>  
In XAML you need to add a CompositeTransform instance to your element if you want to animate the scale or rotation of it. Now you can create a Storyboard to animate the Opacity and Scale of the TextBlock:
  1. <views:MvxWindowsPage.Resources>  
  2.     <Storyboard x:Key="TextBlockAnimation" Duration="0:0:1.5">  
  3.         <DoubleAnimationUsingKeyFrames Storyboard.TargetName="TextHello" Storyboard.TargetProperty="Opacity">  
  4.             <LinearDoubleKeyFrame KeyTime="0:0:0.750" Value="1"/>  
  5.         </DoubleAnimationUsingKeyFrames>  
  6.         <DoubleAnimationUsingKeyFrames Storyboard.TargetName="TextHello" Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.ScaleX)">  
  7.             <LinearDoubleKeyFrame KeyTime="0:0:1.0" Value="2"/>  
  8.             <LinearDoubleKeyFrame KeyTime="0:0:1.5" Value="1"/>  
  9.         </DoubleAnimationUsingKeyFrames>  
  10.         <DoubleAnimationUsingKeyFrames Storyboard.TargetName="TextHello" Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.ScaleY)">  
  11.             <LinearDoubleKeyFrame KeyTime="0:0:1.0" Value="2"/>  
  12.             <LinearDoubleKeyFrame KeyTime="0:0:1.5" Value="1"/>  
  13.         </DoubleAnimationUsingKeyFrames>  
  14.     </Storyboard>  
  15. </views:MvxWindowsPage.Resources>  
And finally you only need to launch the animation, using a behavior or by code in the OnNavigatedTo method:
  1. protected override void OnNavigatedTo(Windows.UI.Xaml.Navigation.NavigationEventArgs e)  
  2. {  
  3.     base.OnNavigatedTo(e);  
  4.   
  5.     var animation = (Storyboard)this.Resources["TextBlockAnimation"];  
  6.     animation.Begin();  
  7. }  
That's all, you have the same animation you made before in Xamarin.Forms, now in Windows and Windows Phone. Now is Android's turn.

Android

In Android you need to use AXML files to create the animation. Let's start creating the TextView to show in your page:
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     xmlns:local="http://schemas.android.com/apk/res-auto"  
  4.     android:orientation="vertical"  
  5.     android:layout_width="fill_parent"  
  6.     android:layout_height="fill_parent">  
  7.   <TextView  
  8.         android:id="@+id/TextHello"  
  9.         android:layout_width="fill_parent"  
  10.         android:layout_height="wrap_content"  
  11.         android:textSize="40dp"  
  12.         android:textColor="#00F"  
  13.         local:MvxBind="Text Hello" />  
  14. </LinearLayout>  
Now it is time to start working with an animation set. Start creating a new AXML file in the Drawable folder inside the Resources folder. Call it TextAnimation, as in the following example:
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <set xmlns:android="http://schemas.android.com/apk/res/android"  
  3.       android:shareInterpolator="false">  
  4.   <alpha android:interpolator="@android:anim/linear_interpolator"  
  5.          android:toAlpha="1"  
  6.          android:startOffset="0"  
  7.          android:duration="750"/>  
  8.   <scale android:interpolator="@android:anim/linear_interpolator"  
  9.          android:scaleGravity="center_vertical"  
  10.          android:toXScale="2"  
  11.          android:toYScale="2"  
  12.          android:pivotX="50%"  
  13.          android:pivotY="50%"  
  14.          android:startOffset="0"  
  15.          android:duration="1000"/>  
  16.   <scale android:interpolator="@android:anim/linear_interpolator"  
  17.          android:scaleGravity="center_vertical"  
  18.          android:toXScale="1"  
  19.          android:toYScale="1"  
  20.          android:pivotX="50%"  
  21.          android:pivotY="50%"  
  22.          android:startOffset="1000"  
  23.          android:duration="500"/>  
  24. </set>  
To execute multiple animations over one object in Android, you need to create a SET. It behaves in a way like the XAML Storyboards. Then you can use various AXML objects like Alpha, Scale and Rotate to animate the object. All the animations here are all launched together, so you need to use the StartOffset property if you want to make any of them launch after another. And voilá! our animation is done and working!

iOS

Last but not least, iOS. Since the iOS interface is created in C# you can take advantage of it to easily create awesome animations. As with the previous platforms, start creating the screen contents in the override ViewDidLoad method:
  1. public override void ViewDidLoad()  
  2. {  
  3.     View = new UIView { BackgroundColor = UIColor.White };  
  4.     base.ViewDidLoad();  
  5.   
  6.     // ios7 layout  
  7.     if (RespondsToSelector(new Selector("edgesForExtendedLayout")))  
  8.     {  
  9.         EdgesForExtendedLayout = UIRectEdge.None;  
  10.     }  
  11.   
  12.     var label = new UILabel(new CGRect(10, 100, 300, 60));  
  13.     label.Alpha = 0f;  
  14.     label.TextColor = UIColor.Blue;  
  15.     Add(label);  
  16.   
  17.     var set = this.CreateBindingSet<FirstView, Core.ViewModels.FirstViewModel>();  
  18.     set.Bind(label).To(vm => vm.Hello);  
  19.     set.Apply();  
  20. }  
Now you can use the Animate method of the UIView class to define and create your animation as in the following:
  1. private void CreateLabelAnimation(UILabel label)  
  2. {  
  3.     UIView.Animate(0.75, 0, UIViewAnimationOptions.CurveLinear,  
  4.     () =>  
  5.     {  
  6.         label.Alpha = 1f;  
  7.     }, null);  
  8.     UIView.Animate(1, 0, UIViewAnimationOptions.CurveLinear,  
  9.     () =>  
  10.     {  
  11.         label.Transform = CGAffineTransform.MakeScale(2f, 2f);  
  12.     }, null);  
  13.     UIView.Animate(0.5, 1, UIViewAnimationOptions.CurveLinear,  
  14.     () =>  
  15.     {  
  16.         label.Transform = CGAffineTransform.MakeScale(1f, 1f);  
  17.     }, null);  
  18. }  
Animate the method has the following five parameters:
  • Animation duration, in seconds

  • Animation offset in seconds, before start.

  • Type of easing/transition function to use from UIViewAnimationOptions enum.

  • An action (void method without parameters) to execute. Here is where you can use the element transformations to animate them.

  • An action (void method without parameters) to execute when the animation has finished.
The animation code above is so simple, it is nearly self-explanatory. The first animation simply increases the Alpha to 1 at 750 milliseconds with a linear easing function.

For the scale, you can use the MakeScale method of the CGAffineTransform object to create a transform for the element.

Finally

To end, you can grab the source code for all these samples in my GitHub account here. I hope this little article and sample code help you make awesome animations in your apps.

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now