12.1 Using pre-defined animations
Xamarin.Forms comes with a set of pre-defined animations like translation, rotation, scale and fading. In this example we will create a button that scales and rotates back and forth when pressed.
First we create a simple button
var button = new Button {
Text = "Animate!",
HorizontalOptions = LayoutOptions.CenterAndExpand,
VerticalOptions = LayoutOptions.CenterAndExpand,
};
and add it to the MainPage:
MainPage = new ContentPage { Content = button };
The button Command contains the actual animation code. Since we will await certain lines of code, the whole delegate has to be marked with the async keyword.
button.Command = new Command(async () => {
button.ScaleTo(3, 1000, Easing.CubicInOut);
await button.RotateTo(15, 1000, Easing.CubicInOut);
button.ScaleTo(1, 1000, Easing.CubicInOut);
await button.RotateTo(0, 1000, Easing.CubicInOut);
});
The first line scales the button to its triple size over a time of 1000 milliseconds. The easing CubicInOut lets the animation start slowly, than accelerate in the middle and decelerate when reaching the target state. Note that this line is not awaited. Thus the next animation is started immediately, without waiting for the first one to finish. The button is rotated to an angle of 15 degrees. This line is awaited: The execution of the Command pauses, until the rotation is complete. Because the time spans are equal, the scaling will just finish together with the rotation.) Last but not least, we repeat this combination of animations to scale and rotate back to the original state.