WPF - animate image source change

13,237

A pure XAML solution could look like this, of course with different images and timings.

<Image>
    <Image.Triggers>
        <EventTrigger RoutedEvent="Loaded">
            <BeginStoryboard>
                <Storyboard RepeatBehavior="Forever">
                    <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Source"
                                                   Duration="0:0:2">
                        <DiscreteObjectKeyFrame KeyTime="0:0:0">
                            <DiscreteObjectKeyFrame.Value>
                                <BitmapImage UriSource="C:\Users\Public\Pictures\Sample Pictures\Koala.jpg"/>
                            </DiscreteObjectKeyFrame.Value>
                        </DiscreteObjectKeyFrame>
                        <DiscreteObjectKeyFrame KeyTime="0:0:1">
                            <DiscreteObjectKeyFrame.Value>
                                <BitmapImage UriSource="C:\Users\Public\Pictures\Sample Pictures\Penguins.jpg"/>
                            </DiscreteObjectKeyFrame.Value>
                        </DiscreteObjectKeyFrame>
                    </ObjectAnimationUsingKeyFrames>
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger>
    </Image.Triggers>
</Image>
Share:
13,237
Rob McCabe
Author by

Rob McCabe

Software developer from Northern Ireland. I use technologies such as .net Core, Angular, Docker, Kubernetes and much more!

Updated on June 14, 2022

Comments

  • Rob McCabe
    Rob McCabe almost 2 years

    I'm pretty new to WPF but I think what I need to do is relatively simple. I need to create an image "animation", where I am changing an image source every .25 of a second.

    I have a folder named "animation" with images 1 to 25 png live (named 1.png, 2.png... 25.png). Each image correlate to different frame of my animation.

    I want to write xaml to change the image from 1 to 2, from 2 to 3, for 3 to 4 etc every .25 seconds until it gets to the 25th image, then it should loop back to the start.

    I most likely will need to write some c# to do this. I want it to run on a thread that can interact with the UI (as in update the image) but not block the UI thread.

    Thanks in advance!