Search code examples
c#wpfuser-interfacepng

How to present multiple PNG images as GIF in wpf?


I studying a wpf project. I have 40 PNG files with transparent backgrounds, and when I stitch them together, they work like a natural loading bar. I don't want to make it into a GIF, but rather like loading something into the UI in PNG format.

The attempts I've made are as follows:

  1. Repetitive implementation using UI Thread: I found a huge consumption of resources. It is considered unsuitable.
  2. WpfAnimatedGif library: It is considered inappropriate to use the desired 40 PNG files.

If you have any good ideas, please reply.


Solution

  • Assuming you have in your XAML an Image element named image and your paths to the png files in a List<string> named imagePaths you can use a timer:

    private void UpdateLoadingBar()
    {
        var frameIndex = 0;
        var frameCount = imagePaths.Count;
            
        var timer = new DispatcherTimer();
        timer.Interval = TimeSpan.FromMilliseconds(100);
        timer.Tick += (sender, e) =>
        {
            loadingImage.Source = new BitmapImage(
                new Uri(imagePaths[frameIndex], UriKind.RelativeOrAbsolute));
    
            if (++frameIndex >= frameCount)
            {
                // Stop the timer when all frames have been displayed
                timer.Stop();
            }
        };
    
        timer.Start();
    }
    

    Or if you are familiar with async programming you could use

    private async Task UpdateLoadingBar()
    {
        foreach (var imagePath in imagePaths)
        {
            loadingImage.Source = new BitmapImage(
                new Uri(imagePath, UriKind.RelativeOrAbsolute));
    
            // Delay between each frame (adjust the duration as needed)
            await Task.Delay(100);
        }
    }
    

    This needs to be started from an async event handler like:

    private async void StartLoadingButton_Click(object sender, RoutedEventArgs e)
    {
        await UpdateLoadingBar();
    }