Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin Forms - animate a change of image source with C#

I'm looking to see if there is a way to make a change if image source appear as if it is sliding in, much like a carousel.

I had a look at this post but here the answer suggests a simple animation, not a slide in effect, my set-up is similar to the above mention post in that my image source is bound to a variable in a view model.

Is there any way to achieve this?

like image 328
DarkW1nter Avatar asked Mar 07 '23 04:03

DarkW1nter


1 Answers

The defaults animation features Xamarin.Forms provides is enough to achieve what you want.

Following the @Johannes's idea, for example, you can have a nice animation.

Here's an implementation:

XAML

<Image x:Name="image" 
       Source="Icon"
       HorizontalOptions="CenterAndExpand"/>
<Button Clicked="Button_Clicked"
        Text="Animate"
        HorizontalOptions="Center"/>

Code behind

private async void Button_Clicked(object sender, EventArgs e)
{
    uint transitionTime = 600;
    double displacement = image.Width;

    await Task.WhenAll(
        image.FadeTo(0, transitionTime, Easing.Linear),
        image.TranslateTo(-displacement, image.Y, transitionTime, Easing.CubicInOut));

    // Changes image source.
    image.Source = ImageSource.FromFile("Icon");

    await image.TranslateTo(displacement, 0, 0);
    await Task.WhenAll(
        image.FadeTo(1, transitionTime, Easing.Linear),
        image.TranslateTo(0, image.Y, transitionTime, Easing.CubicInOut));
}

Result

enter image description here

I hope it helps.

like image 138
Diego Rafael Souza Avatar answered Mar 13 '23 06:03

Diego Rafael Souza