每秒更新的BitmapImage闪烁问题

4

我正在尝试通过每秒设置源属性来更新图像,这样可以实现更新,但会在更新时导致闪烁。

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

如果我不设置IgnoreImageCache,图片将不会更新,也就没有闪烁了。有没有一种方法来避免这个缺点呢?祝好。

您可以先完全下载图像缓冲区,然后从该缓冲区创建一个MemoryStream,最后创建一个新的BitmapImage并分配其StreamSource属性。 - Clemens
我尝试使用BmpBitmapEncoder来实现,但它会导致相同的闪烁问题。 - bl4kh4k
为什么需要编码器?您想解码一张图片。我将提供一些示例代码。 - Clemens
1个回答

4
下面的代码片段在将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));

谢谢Clemens,我甚至没有想到使用WebClient。干杯。 - bl4kh4k

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接