當WPF遇到了gif

WPF很強大,但是當WPF的image控件遇到gif時就只讀了圖片的第一幀,很好很強大!

  WPF不屑於gif的簡單動畫!

  但是這對程序員來說不大爽啊!急得我眼淚都下來了!

  幸好WPF裏有MediaElement這個東西,它是對MediaPlyer的一個封裝,果然很強大啊。不過另我不爽的是我這裏有N個gif圖片就要有N個MediaElement,要了親命了。

  還是不好,如果你能想到用WebBrowseControl來實現,或者用Frame來實現,恭喜你,你太有才了!

  我還是不想這麼去做,才分不夠啊!

  重寫一下WPF的image,good idea!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
public class GIFImageControl : System.Windows.Controls.Image
    {
        delegate void OnFrameChangedDelegate();
        private Bitmap m_Bitmap;
        public string Path { get; set; }
        BitmapSource bitmapSource;

        public void AnimatedImageControl(string path)
        {
            Path = path;
            m_Bitmap = (Bitmap)Image.FromFile(path);
            Width = m_Bitmap.Width;
            Height = m_Bitmap.Height;
            ImageAnimator.Animate(m_Bitmap, OnFrameChanged);
            bitmapSource = GetBitmapSource();
            Source = bitmapSource;

        }


        private void OnFrameChanged(object sender, EventArgs e)
        {

            Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                                   new OnFrameChangedDelegate(OnFrameChangedInMainThread));

        }

        private void OnFrameChangedInMainThread()
        {
            ImageAnimator.UpdateFrames();
            if (bitmapSource != null)
                bitmapSource.Freeze();
            bitmapSource = GetBitmapSource();
            Source = bitmapSource;
            InvalidateVisual();
        }

        //private static bool loaded;
        private BitmapSource GetBitmapSource()
        {
            IntPtr inptr = m_Bitmap.GetHbitmap();
            bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(
                inptr, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
            DeleteObject(inptr);
            return bitmapSource;
        }

        [DllImport("gdi32")]
        static extern int DeleteObject(IntPtr o);
    }

  ok,用window原有的東西去綁定到wpf上去。很好吧!是不是也比較有才呢?

本文來自CH似水年華的博客,原文地址: http://hi.baidu.com/mych/blog/item/1eb14f545f12a752564e00be.html

發佈了34 篇原創文章 · 獲贊 8 · 訪問量 15萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章