在WinRT中,如何加载图像,然后只有在写入图像之前只需加载图像即可加载?

b.p*_*ell 2 filepicker writeablebitmap async-await writeablebitmapex windows-runtime

我在WinRT项目中使用WriteableBitmapEx.我将图像加载到用户图片库的WriteableBitmap中.但是,我不能立即写入该图像,如果我这样做,它将被图像本身覆盖(看起来它是异步加载图像然后它覆盖我的绘图在它上面).我不知道如何阻止它(我尝试在SetSource上使用Await,但这不是Async方法).

我已经使用了"Await Task.Delay(1000)"并且有效,但它看起来很hacky因为1000ms可能或者可能没有足够的时间..我希望它等到位图加载后再继续.

任何人都可以看出我做错了什么或建议我如何确保在进行任何处理之前从图片库加载WriteableBitmap?这是我创建的示例代码段:

Dim file = Await picker.PickSingleFileAsync

If file Is Nothing Then
    Exit Sub
End If

Dim wbm As New WriteableBitmap(1, 1)
wbm.SetSource(Await file.OpenAsync(Windows.Storage.FileAccessMode.Read))

' If I don't have this, the DrawLine will not show up, if I do, it will.
Await Task.Delay(1000)

wbm.DrawLine(1, 1, 255, 255, Colors.Green)
wbm.Invalidate()

ImageMain.Source = wbm
Run Code Online (Sandbox Code Playgroud)

Ren*_*lte 8

此方法从应用程序的内容加载图像,对其进行解码并传回即用型WriteableBitmap.取自WriteableBitmapEx库:

/// <summary>
/// Loads an image from the applications content and fills this WriteableBitmap with it.
/// </summary>
/// <param name="bmp">The WriteableBitmap.</param>
/// <param name="uri">The URI to the content file.</param>
/// <returns>The WriteableBitmap that was passed as parameter.</returns>
public static async Task<WriteableBitmap> FromContent(this WriteableBitmap bmp, Uri uri)
{
   // Decode pixel data
   var file = await StorageFile.GetFileFromApplicationUriAsync(uri);
   var decoder = await BitmapDecoder.CreateAsync(await file.OpenAsync(FileAccessMode.Read));
   var transform = new global::Windows.Graphics.Imaging.BitmapTransform();
   var pixelData = await decoder.GetPixelDataAsync(decoder.BitmapPixelFormat, decoder.BitmapAlphaMode, transform, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.ColorManageToSRgb);
   var pixels = pixelData.DetachPixelData();

   // Copy to WriteableBitmap
   bmp = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight);
   using (var bmpStream = bmp.PixelBuffer.AsStream())
   {
      bmpStream.Seek(0, SeekOrigin.Begin);
      bmpStream.Write(pixels, 0, (int)bmpStream.Length);
      return bmp;
   }
}
Run Code Online (Sandbox Code Playgroud)

顺便说一句,WinRT现在由WriteableBitmapEx正式支持.;) http://kodierer.blogspot.de/2012/05/one-bitmap-to-rule-them-all.html