2013-08-18 116 views
1

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

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

如果我不设置IgnoreImageCache,图像不因此无论是更新无闪烁。

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

干杯。

+0

您可以先下载图像缓冲区,然后从该缓冲区创建一个MemoryStream,最后创建一个新的BitmapImage并分配其'StreamSource'属性。 – Clemens

+0

我尝试过使用BmpBitmapEncoder来做这件事,但它会导致相同的闪烁发生。 – bl4kh4k

+0

为什么选择编码器?你想解码图像。我将提供一些示例代码。 – Clemens

回答

2

下面的代码片段下载整个图像缓冲区之前设置图像的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并在分派器中分配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)); 
+0

谢谢克莱门斯,甚至没有考虑使用WebClient。干杯。 – bl4kh4k