2013-08-18 115 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