Question

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.

Était-ce utile?

La solution

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));
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top