12

I am using this code for gif Animating in seprate library and xaml code in my main project:

<controls:GifImage GifSource="/project;component/Images/my.gif" Stretch="None" />

Gif Animating (seprate file):

public class GifImage : Image
    {
        #region Memmbers

        private GifBitmapDecoder _gifDecoder;
        private Int32Animation _animation;
        private bool _isInitialized;

        #endregion Memmbers

        #region Properties

        private int FrameIndex
        {
            get { return (int)GetValue(FrameIndexProperty); }
            set { SetValue(FrameIndexProperty, value); }
        }

        private static readonly DependencyProperty FrameIndexProperty =
         DependencyProperty.Register("FrameIndex", typeof(int), typeof(GifImage), new FrameworkPropertyMetadata(0, new PropertyChangedCallback(ChangingFrameIndex)));

        private static void ChangingFrameIndex(DependencyObject obj, DependencyPropertyChangedEventArgs ev)
        {
            GifImage image = obj as GifImage;
            image.Source = image._gifDecoder.Frames[(int)ev.NewValue];
        }

        /// <summary>
        /// Defines whether the animation starts on it's own
        /// </summary>
        public bool AutoStart
        {
            get { return (bool)GetValue(AutoStartProperty); }
            set { SetValue(AutoStartProperty, value); }
        }

        public static readonly DependencyProperty AutoStartProperty =
         DependencyProperty.Register("AutoStart", typeof(bool), typeof(GifImage), new UIPropertyMetadata(false, AutoStartPropertyChanged));

        private static void AutoStartPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            if ((bool)e.NewValue)
                (sender as GifImage).StartAnimation();
        }

        public string GifSource
        {
            get { return (string)GetValue(GifSourceProperty); }
            set { SetValue(GifSourceProperty, value); }
        }

        public static readonly DependencyProperty GifSourceProperty =
         DependencyProperty.Register("GifSource", typeof(string), typeof(GifImage), new UIPropertyMetadata(string.Empty, GifSourcePropertyChanged));

        private static void GifSourcePropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            // CARLO 20100622: Reinitialize animation everytime image is changed
            (sender as GifImage).Initialize();
        }

        #endregion Properties

        #region Private Instance Methods

        private void Initialize()
        {

            _gifDecoder = new GifBitmapDecoder(new Uri(String.Format("pack://application:,,,{0}", this.GifSource)), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
            _animation = new Int32Animation(0, _gifDecoder.Frames.Count - 1, new Duration(new TimeSpan(0, 0, 0, _gifDecoder.Frames.Count / 10, (int)((_gifDecoder.Frames.Count / 10.0 - _gifDecoder.Frames.Count / 10) * 1000))));
            _animation.RepeatBehavior = RepeatBehavior.Forever;
            this.Source = _gifDecoder.Frames[0];

            _isInitialized = true;
        }

        #endregion Private Instance Methods

        #region Public Instance Methods

        /// <summary>
        /// Shows and starts the gif animation
        /// </summary>
        public void Show()
        {
            this.Visibility = Visibility.Visible;
            this.StartAnimation();
        }

        /// <summary>
        /// Hides and stops the gif animation
        /// </summary>
        public void Hide()
        {
            this.Visibility = Visibility.Collapsed;
            this.StopAnimation();
        }

        /// <summary>
        /// Starts the animation
        /// </summary>
        public void StartAnimation()
        {
            if (!_isInitialized)
                this.Initialize();

            BeginAnimation(FrameIndexProperty, _animation);
        }

        /// <summary>
        /// Stops the animation
        /// </summary>
        public void StopAnimation()
        {
            BeginAnimation(FrameIndexProperty, null);
        }

        #endregion Public Instance Methods
    }

but i get error:

The URI prefix is not recognized.

I am not sure why i get error. Could someone help me please ?

Mathi901
  • 235
  • 3
  • 14
UFO
  • 400
  • 2
  • 6
  • 16
  • The code appears to come from [this answer](https://stackoverflow.com/a/1134340/294248). There is a higher-voted answer on the same page that uses a NuGet package called "XamlAnimatedGif" (nee "WpfAnimatedGif"), as well as various other solutions. – fadden Dec 13 '19 at 21:28

3 Answers3

30

There is a much easier way to show an animated .gif in wpf - use the MediaElement

Example:

<MediaElement x:Name="myGif" MediaEnded="myGif_MediaEnded" UnloadedBehavior="Manual"     Source="file://C:\waiting.GIF" LoadedBehavior="Play" Stretch="None"/>

If you want the .gif to loop endlessly but it only specifies a limited amount of repeats in the .gif file, you can hook MediaEnded and just restart the animation (Be sure to set the UnloadedBehavior to Manual):

    private void myGif_MediaEnded(object sender, RoutedEventArgs e)
    {
        myGif.Position = new TimeSpan(0, 0, 1);
        myGif.Play();
    }
edtheprogrammerguy
  • 5,957
  • 6
  • 28
  • 47
0

Try this:

<controls:GifImage GifSource="/Images/my.gif" Stretch="None" />

BTW, I found using this way to play gif in wpf might deform some gif images, and I wonder why...

Chobits
  • 65
  • 7
0

I can't take credit for this but here's a way to do this in XAML only. I added an "IsBusy" property to my ViewModel to show/hide the spinner during processing.

        <Image Name="Spinner" Source="Resources/spinner.gif" RenderTransformOrigin="0.5, 0.5">
            <Image.Triggers>
                <EventTrigger RoutedEvent="FrameworkElement.Loaded">
                    <EventTrigger.Actions>
                        <BeginStoryboard>
                            <Storyboard Storyboard.TargetName="Spinner" Storyboard.TargetProperty="RenderTransform.(RotateTransform.Angle)">
                                <DoubleAnimation From="0" To="360" BeginTime="0:0:0" Duration="0:0:2" RepeatBehavior="Forever" />
                            </Storyboard>
                        </BeginStoryboard>
                    </EventTrigger.Actions>
                </EventTrigger>
            </Image.Triggers>
            <Image.RenderTransform>
                <RotateTransform Angle="0" />
            </Image.RenderTransform>
            <Image.Style>
                <Style TargetType="Image">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding IsBusy}" Value="False">
                            <Setter Property="Visibility" Value="Hidden"/>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </Image.Style>
        </Image>

Here's the link to the author's solution.

LawMan
  • 3,469
  • 1
  • 29
  • 32
  • 3
    this is just rotating the image (pics out first image if source is .gif) – Mohammad Mahroz Nov 19 '17 at 15:52
  • The linked page is about replacing an animated-GIF spinner animation with an alternative solution. Two solutions are given, the first of which is shown in the answer (and is not relevant to question). The other uses a WPF [Storyboard](https://learn.microsoft.com/en-us/dotnet/framework/wpf/graphics-multimedia/how-to-animate-a-property-by-using-a-storyboard) to show frames in sequence. This was explored a bit more [in this answer](https://stackoverflow.com/a/5519381/294248). – fadden Dec 13 '19 at 21:24