我是新來做C#Windows Phone編程。更好的方式來在Windows Phone上同步加載圖像?
概括地說,我目前正在建設一個應用程序,將:
負載image A
負載image B
,然後加載image C
然後用這3個圖像做一些崗位處理。
我的圖像B和圖像C在項目中構建爲Content
。 圖片A是從圖庫中選擇或通過相機拍攝的,或者我們可以簡單地假設圖片A是從獨立存儲加載的。
我遇到了一個我認爲是由異步圖像加載引起的問題。
這裏是我的代碼:
...
// I intend to load the 3 pictures by calling the method: LoadImage(int id) and LoadCImage();
else if (ListBox.SelectedIndex == 0)
{
Debug.WriteLine("Selected 0");
PhotoProcessor pp = new PhotoProcessor();
WriteableBitmap imageA = new WriteableBitmap(AImage);
WriteableBitmap imageB = LoadImage(0);
WriteableBitmap imageC = LoadCImage();
WriteableBitmap mix = pp.Mix(pp.CalcAverageColour(0), imageA, imageB, imageC);
resultPic.Source = mix;
}
...
和:
private WriteableBitmap LoadImage(int id)
{
//String uriString = "/Assets/img0.jpg";
//BitmapImage img = new BitmapImage(new Uri(uriString, UriKind.Relative));
BitmapImage img = new BitmapImage();
img.CreateOptions = BitmapCreateOptions.None;
//img.SetSource(Application.GetResourceStream(new Uri("/Assets/facetemplate0.jpg", UriKind.Relative)).Stream);
img.UriSource = new Uri("/Assets/img" + id + ".jpg", UriKind.Relative);
//img.UriSource = new Uri(uriString, UriKind.Relative);
return new WriteableBitmap(img);
}
private WriteableBitmap LoadCImage()
{
//BitmapImage img = new BitmapImage(new Uri("/Assets/imgC.jpg", UriKind.Relative));
BitmapImage bmp = new BitmapImage();
bmp.CreateOptions = BitmapCreateOptions.None;
//img.SetSource(Application.GetResourceStream(new Uri("/Assets/imgC.jpg", UriKind.Relative)).Stream);
bmp.UriSource = new Uri("/Assets/imgC.jpg", UriKind.Relative);
return new WriteableBitmap(bmp);
}
現在我的問題是:
當我試圖運行這段代碼,它會拋出一個空引用異常,這是因爲函數mix
無法加載Image AB和C(加載這些圖像是異步的)。
我不知道是否有辦法讓我順序加載這些圖像,然後讓我把它們傳遞給mix
函數?
我已經試過什麼:
通過檢查this great blog post,我能知道,確實有一些方法來同步加載圖像,但你可以在我的代碼中看到的,我試過像使用博客帖一樣使用
SetSource(stream)
,但不幸的是我得到了相同的空引用異常。我也想過
EventHandler
方法,但我不認爲它在這種情況下是個好主意。如果我實現EventHandler
,它會是這樣的(僞代碼):imageA_Opened() { LoadImageB += imageB_Opened(); } imageB_Opened() { LoadImageC += imageC_Opened(); } imageC_Opened() { PhotoProcessor pp = new PhotoProcessor(); pp.Mix(averageColour, A, B, C); }
我說得對不對?
感謝您的快速反應。所以在我的僞代碼中的想法是更好的方法?通過使用3個'EventHandler's? – dumbfingers
@ ss1271是的。 – Servy
謝謝,我會嘗試。 – dumbfingers