在StoryBoard中改变图像的来源

本文关键字:图像 改变 StoryBoard | 更新日期: 2023-09-27 18:03:55

我试图在我的主页上有多个图像(大约30),通过使用StoryBoard淡入和淡出。目前,我在一张图片上完美地完成了动画,它看起来是这样的;

private void OnDashboardPageLoaded(object sender, RoutedEventArgs e)
{
    Storyboard storyboard = new Storyboard();
    TimeSpan duration = new TimeSpan(0, 0, 10);
    // Create a DoubleAnimation to fade the not selected option control
    DoubleAnimation animation = new DoubleAnimation();
    animation.From = 0.0;
    animation.To = 1.0;
    animation.Duration = new Duration(duration);
    // Configure the animation to target de property Opacity
    Storyboard.SetTargetName(animation, testImage.Name);
    Storyboard.SetTargetProperty(animation, new PropertyPath(OpacityProperty));
    // Add the animation to the storyboard
    storyboard.Children.Add(animation);
    storyboard.RepeatBehavior = RepeatBehavior.Forever;
    animation.AutoReverse = true;
    // Begin the storyboard
    storyboard.Begin(this);
}

And my XAML;

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition />
    </Grid.RowDefinitions>
    <Image Source="http://www.online-image-editor.com/styles/2013/images/example_image.png" x:Name="testImage" Stretch="Uniform" />
</Grid>

正如你所看到的,我在这里设置了一个静态源,但最终我想做的是加载目录中的所有图像,并在每个动画结束时更改源,以便每次都显示新图像(直到所有30个都显示出来),我该怎么做呢?

编辑:故事板完成后;

storyboard.Completed += new EventHandler(Story_Completed); // In OnDashboardPageLoaded method
private void Story_Completed(object sender, EventArgs e)
{
    storyboard.Begin(this);
}

在StoryBoard中改变图像的来源

下面的方法淡出一个Image控件,改变它的Source属性,然后再次淡出。你可以用另一个ImageSource参数循环地调用它(例如,由DispatcherTimer控制)。

public static void ShowNextImage(Image image, ImageSource source, TimeSpan fadeTime)
{
    if (image.Source == null) // no fade out
    {
        image.Source = source;
        image.BeginAnimation(UIElement.OpacityProperty,
            new DoubleAnimation(0d, 1d, fadeTime));
    }
    else
    {
        var fadeOut = new DoubleAnimation(0d, fadeTime);
        fadeOut.Completed += (s, e) =>
        {
            image.Source = source;
            image.BeginAnimation(UIElement.OpacityProperty,
                new DoubleAnimation(1d, fadeTime));
        };
        image.BeginAnimation(UIElement.OpacityProperty, fadeOut);
    }
}