Update BitmapImage every second flickers

陌路散爱 提交于 2020-02-24 09:26:07

问题


I am trying to update an image by setting the source property every second, this works however causes a flicker when updated.

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

If I don't set IgnoreImageCache, the image does not update thus no flickering either.

Is there a way around this caveat?

Cheers.


回答1:


The following code snippet downloads the whole image buffer before setting the Image's Source property to a new BitmapImage. This should eliminate any flicker.

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;

If the download takes some time, it would make sense to run it in a separate thread. You would then have to take care for proper cross-thread access by also calling Freeze on the BitmapImage and assigning Source in the Dispatcher.

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));


来源:https://stackoverflow.com/questions/18302424/update-bitmapimage-every-second-flickers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!