【问题标题】:Animate a BackgroundImage of a ContentPage为 ContentPage 的 BackgroundImage 设置动画
【发布时间】:2018-08-23 18:25:27
【问题描述】:

到目前为止,我还没有找到这个简单问题的任何答案:

如何为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;

现在我想玩这个背景,而不是改变它,我非常想模仿 Apple 的照片在幻灯片上所做的事情:

  • 最初背景是1.jpg
  • 移动用动画朝一个方向移动
  • 淡入背景到2.jpg
  • 冲洗并在两者之间重复循环图像

但是,我不知道如何检索图像对象以便对其进行动画处理。

请注意,我不想要gif,只想要简单的静止图像。

【问题讨论】:

  • 请阅读文档。你正在做的不是动画。 docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/…
  • @Greggz 我现在所做的不是,但我想要的是为页面的BackgroundImage 设置动画,而不是页面内的图像(我可以轻松地做到这一点)。跨度>
  • 假设您也可以获得Image 参考,我看不出有什么不同。请发布您尝试执行此操作的实际代码

标签: xamarin xamarin.forms


【解决方案1】:

查看PageRenderer 源代码 (see here for Android),您可以很容易地看到,没有像您假设的那样底层 Image

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

他们宁愿直接在本机控件中设置它。这意味着您必须模仿背景图像才能获得可动画性(这个词甚至存在吗?)。

我不会给你准备好使用源代码,但我用Grid 实现了类似的东西(AbsoluteLayout 也可能)

  • Grid 各有一行和一列
  • 包含背景的 Image 应添加在任何其他子项之前(在集合中,不一定是临时的)
  • 如果没有背景Image,则直接添加新的背景图片
  • 如果已有背景图片,则添加新的背景图片,Opacity 等于 0
  • 创建两个动画
  • 一个用来淡出旧图像的方法
  • 一个用于淡入新图像的功能

代码:

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));
}

由于我使用的是TranslateTo 而不是Animate,所以我的确切代码看起来有点不同,但这应该可以。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-29
    • 1970-01-01
    相关资源
    最近更新 更多