senseiwa
senseiwa

Reputation: 2489

Animate a BackgroundImage of a ContentPage

So far I have not found any answers to this simple question:

How can I animate a BackgroundImage?

BackgroundImage = "1.jpg"; // <--- initial

countdown = new System.Timers.Timer();

countdown.Interval = 2000;
countdown.Elapsed += (sender, e) => 
{
    if (BackgroundImage == "1.jpg")
    {
        System.Diagnostics.Debug.WriteLine("change background to 2");

        Device.BeginInvokeOnMainThread(() =>
        {
            BackgroundImage = "marcus.jpg";
        });

    }
    else
    {
        System.Diagnostics.Debug.WriteLine("change background to 1");

        Device.BeginInvokeOnMainThread(() =>
        {
            BackgroundImage = "1.jpg";
        });
    }

};
countdown.Enabled = true;

Now I would like to play with this background, instead of changing it I would very much like to mimic what Apple's Photos does with a slideshow:

I don't know, however, how to retrieve the image object so that I can animate it.

Note that I don't want a gif, just simple still images.

Upvotes: 0

Views: 124

Answers (1)

Paul Kertscher
Paul Kertscher

Reputation: 9713

Having a look at PageRenderer source code (see here for Android), you can easily see, that there is no underlying Image like you assumed

void UpdateBackgroundImage(Page view)
{
    if (!string.IsNullOrEmpty(view.BackgroundImage))
        this.SetBackground(Context.GetDrawable(view.BackgroundImage));
}

they rather set it direcly in the native control. This means that you'll have to mimic the background image in order to achive animatability (does this word even exist?).

I won't give you ready to use source code, but I achieved something similar with a Grid (AbsoluteLayout might be possible, too)

  • The Grid has a single row and column each
  • The Image containing the background should be added before (within the collection, not necessarily temporary) any other children
  • If there is not background Image, yet, a new background image will be added directly
  • If there is a background image already, the new one is added with Opacity equal 0
  • Create two animations
  • One to fade the old image out
  • One to fade the new image in

Code:

private void FadeViews(View newView, View currentView)
{
    newView.Opacity = 0;
    Grid.Children.Insert(0, newView);

    newView.Animate("FadeIn", d => newView.Opacity = d, 0, 1);
    newView.Animate("FadeOut", d => currentView.Opacity = d, 1, 0, finished: (_, __) => this.Grid.Children.Remove(currentView));
}

Since I am using TranslateTo instead of Animate, my exact code looks a bit different, but this should do.

Upvotes: 1

Related Questions