C# 更新BitmapImage每秒闪烁一次
我试图通过每秒设置source属性来更新图像,但这样做可以在更新时引起闪烁C# 更新BitmapImage每秒闪烁一次,c#,wpf,bitmapimage,C#,Wpf,Bitmapimage,我试图通过每秒设置source属性来更新图像,但这样做可以在更新时引起闪烁 CurrentAlbumArt = new BitmapImage(); CurrentAlbumArt.BeginInit(); CurrentAlbumArt.UriSource = new Uri((currentDevice as AUDIO).AlbumArt); CurrentAlbumArt.CreateOptions = BitmapCreateOptions.IgnoreImageCache; Curr
CurrentAlbumArt = new BitmapImage();
CurrentAlbumArt.BeginInit();
CurrentAlbumArt.UriSource = new Uri((currentDevice as AUDIO).AlbumArt);
CurrentAlbumArt.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
CurrentAlbumArt.EndInit();
如果我不设置IgnoreImageCache
,图像不会更新,因此也不会闪烁
有办法绕过这个警告吗
干杯。在将图像的
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));
您可以先完全下载图像缓冲区,然后从该缓冲区创建一个MemoryStream,最后创建一个新的BitmapImage并分配其
StreamSource
属性。我曾尝试使用BmpBitmapEncoder进行此操作,但它会导致相同的闪烁。为什么使用编码器?您想要解码图像。我将提供一些示例代码。感谢Clemens,他甚至没有想过使用WebClient。干杯