Last active
February 11, 2018 03:00
-
-
Save lindexi/7c6d70c821fcb72f487812e58c564442 to your computer and use it in GitHub Desktop.
WPF 使用 WinForm 播放 gif
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// 使用 WinForm 播放 Gif | |
/// </summary> | |
/// <example> | |
/// xaml: | |
/// <local:GifImageControl x:Name="Image" Path="lindexi.gif"></local:GifImageControl> | |
/// cs: | |
/// var image = new GifImageControl("E:\\lindexi.gif"); | |
/// Grid.Children.Add(image); | |
/// </example> | |
public class GifImageControl : Image | |
{ | |
/// <inheritdoc /> | |
public GifImageControl() | |
{ | |
} | |
/// <inheritdoc /> | |
public GifImageControl(string path) | |
{ | |
Path = path; | |
} | |
/// <summary> | |
/// 图片的地址 | |
/// </summary> | |
public string Path | |
{ | |
get => _path; | |
set | |
{ | |
if (!File.Exists(value)) | |
{ | |
var file = new FileInfo(value); | |
if (!file.Exists) | |
{ | |
throw new ArgumentException("找不到文件" + value); | |
} | |
value = file.FullName; | |
} | |
_path = value; | |
Start(); | |
} | |
} | |
/// <summary> | |
/// 播放图片 | |
/// </summary> | |
public void Start() | |
{ | |
if (_bitmap != null) | |
{ | |
//多次点击播放,如果没有停止,会让上一个图片还在播放 | |
Stop(); | |
} | |
var path = Path; | |
_bitmap = (Bitmap) System.Drawing.Image.FromFile(path); | |
ImageAnimator.Animate(_bitmap, OnFrameChanged); | |
_bitmapSource = GetBitmapSource(); | |
Source = _bitmapSource; | |
} | |
/// <summary> | |
/// 停止播放 | |
/// </summary> | |
public void Stop() | |
{ | |
if (_bitmap == null) | |
{ | |
return; | |
} | |
ImageAnimator.StopAnimate(_bitmap, OnFrameChanged); | |
_bitmap.Dispose(); | |
_bitmap = null; | |
} | |
private Bitmap _bitmap; | |
private BitmapSource _bitmapSource; | |
private string _path; | |
private void OnFrameChanged(object sender, EventArgs e) | |
{ | |
Dispatcher.InvokeAsync(OnFrameChangedInMainThread); | |
} | |
private void OnFrameChangedInMainThread() | |
{ | |
ImageAnimator.UpdateFrames(); | |
_bitmapSource = GetBitmapSource(); | |
Source = _bitmapSource; | |
InvalidateVisual(); | |
} | |
private BitmapSource GetBitmapSource() | |
{ | |
IntPtr inptr = _bitmap.GetHbitmap(); | |
_bitmapSource = Imaging.CreateBitmapSourceFromHBitmap( | |
inptr, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); | |
DeleteObject(inptr); | |
return _bitmapSource; | |
} | |
[DllImport("gdi32.dll", CharSet = CharSet.Auto, SetLastError = true)] | |
[return: MarshalAs(UnmanagedType.Bool)] | |
private static extern bool DeleteObject(IntPtr hObject); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment