每秒更新BitmapImage都会闪烁

时间:2013-08-18 18:34:51

标签: c# wpf bitmapimage

我试图通过每秒设置一次源属性来更新图像,但是这会在更新时导致闪烁。

CurrentAlbumArt = new BitmapImage();
CurrentAlbumArt.BeginInit();
CurrentAlbumArt.UriSource = new Uri((currentDevice as AUDIO).AlbumArt);
CurrentAlbumArt.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
CurrentAlbumArt.EndInit();

如果我没有设置IgnoreImageCache,图像就不会更新,因此也不会闪烁。

有没有办法解决这个警告?

干杯。

1 个答案:

答案 0 :(得分:3)

以下代码段在将Image的Source属性设置为新的BitmapImage之前下载整个图像缓冲区。这应该消除任何闪烁。

var webClient = new WebClient();
var url = ((currentDevice as AUDIO).AlbumArt;
var bitmap = new BitmapImage();

using (var stream = new MemoryStream(webClient.DownloadData(url)))
{
    bitmap.BeginInit();
    bitmap.CacheOption = BitmapCacheOption.OnLoad;
    bitmap.StreamSource = stream;
    bitmap.EndInit();
}

image.Source = bitmap;

如果下载需要一些时间,那么在单独的线程中运行它是有意义的。然后,您还必须通过调用BitmapImage上的Freeze并在Dispatcher中分配Source来注意正确的跨线程访问。

var bitmap = new BitmapImage();

using (var stream = new MemoryStream(webClient.DownloadData(url)))
{
    bitmap.BeginInit();
    bitmap.CacheOption = BitmapCacheOption.OnLoad;
    bitmap.StreamSource = stream;
    bitmap.EndInit();
}

bitmap.Freeze();
image.Dispatcher.Invoke((Action)(() => image.Source = bitmap));