2012-12-08 44 views
1

我在連接到Image控件的Windows Phone 8應用程序中有WriteableBitmap。我循環遍歷圖像的每一行,並異步繪製一行像素,然後安排下一行進行繪製。但是,似乎更改底層像素數據不會觸發更改的屬性,因此控件不會更新。如果我將圖像源設置爲使用相同像素創建的新的WriteableBitmap,則圖像更新正常,但我正在進行大量的過度數組複製。對WriteableBitmap像素的更改不會更新屏幕

void PaintImage(object state) 
{ 
    // get my height, width, row, etc. from the state 
    int[] bitmapData = new int[width]; 
    // load the data for the row into the bitmap 

    Dispatcher.BeginInvoke(() => 
    { 
     var bitmap = ImagePanel.Source as WriteableBitmap; 
     Array.Copy(bitmapData, 0, bitmap.Pixels, row * width, bitmapData.Length); 

     if (row < height - 1) 
     { 
      var newState = ... // create new state 
      ThreadPool.QueueUserWorkItem(PaintImage, newState); 
     } 
    }); 
} 

如果我添加上述Array.Copy後這些行,位圖逐漸被吸引到屏幕(雖然在現實中,它只是替換位圖每次):

var newBitmap = new WriteableBitmap(width, height); 
Array.Copy(bitmap.Pixels, newBitmap.Pixels, newBitmap.Pixels.Length); 
ImagePanel.Source = newBitmap; 

好像我需要手動讓WriteableBitmap觸發一些屬性更改通知,以便擁有它的圖像。我猜這個問題會消失,如果我將圖像綁定到ViewModel中的WriteableBitmap?

+0

你不能等待整個畫面以完成繪製,然後更換整個imageSource與新的更新圖片? – robertk

+0

不,這不是我想要的功能。 – sohum

+0

然後,最簡單的方法可能是綁定到一個虛擬機,每次你想要刷新圖片時都會執行RaisePropertyChanged()。 – robertk

回答

1

只需添加一個髒矩形

_myBitmap.Lock(); 
_myBitmap.AddDirtyRect(new Int32Rect(0, 0, _myBitmap.PixelWidth, _myBitmap.PixelHeight)); 
_myBitmap.Unlock(); 

,或者如果你是一個後臺線程

Application.Current.Dispatcher.InvokeAsync(() => 
    { 
     _myBitmap.Lock(); 
     _myBitmap.AddDirtyRect(new Int32Rect(0, 0, _myBitmap.PixelWidth, _myBitmap.PixelHeight)); 
     _myBitmap.Unlock(); 
    });