在 UWP 中使用 RenderTargetBitmap 时出错

Error using using RenderTargetBitmap in UWP

我正在尝试创建位图图像,并具有以下代码:

RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(uielement);

IBuffer pixels = await renderTargetBitmap.GetPixelsAsync();

. . .

var pixelArray = pixels.ToArray();

为了获得 ToArray() 延期,我遇到了 this 问题。所以我补充说:

using System.Runtime.InteropServices.WindowsRuntime; // For ToArray

到我的代码。但是,当我 运行 时,出现以下错误:

Exception thrown: 'System.ArgumentException' in System.Runtime.WindowsRuntime.dll

Additional information: The specified buffer index is not within the buffer capacity.

当我深入了解细节时,堆栈跟踪中显示:

at >System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeBufferExtensions.ToArray(IBuffer source, UInt32 sourceIndex, Int32 count) at >System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeBufferExtensions.ToArray(IBuffer source)

这种提取像素数组的方法是否仍然适用于UWP?如果是,是否有任何方法可以从此错误消息中获取更多详细信息?

那种提取像素数组的方法,绝对适用于UWP。至于错误,反编译后的ToArray()是这样的:

public static byte[] ToArray(this IBuffer source)
{
  if (source == null)
    throw new ArgumentNullException("source");
  return WindowsRuntimeBufferExtensions.ToArray(source, 0U, checked ((int) source.Length));
}

换句话说,它调用了带有起始索引和长度的 ToArray 重载:

public static byte[] ToArray(this IBuffer source, uint sourceIndex, int count)
{
  if (source == null)
    throw new ArgumentNullException("source");
  if (count < 0)
    throw new ArgumentOutOfRangeException("count");
  if (sourceIndex < 0U)
    throw new ArgumentOutOfRangeException("sourceIndex");
  if (source.Capacity <= sourceIndex)
    throw new ArgumentException(SR.GetString("Argument_BufferIndexExceedsCapacity"));
  if ((long) (source.Capacity - sourceIndex) < (long) count)
    throw new ArgumentException(SR.GetString("Argument_InsufficientSpaceInSourceBuffer"));
  byte[] destination = new byte[count];
  WindowsRuntimeBufferExtensions.CopyTo(source, sourceIndex, destination, 0, count);
  return destination;
}

几乎可以肯定导致您问题的行:

  if (source.Capacity <= sourceIndex)
    throw new ArgumentException(SR.GetString("Argument_BufferIndexExceedsCapacity"));

...并且由于 sourceIndex 必然为 0,这意味着 source.Capacity 也为 0。

我建议您在代码中添加一些工具来检查 IBuffer:

RenderTargetBitmap rtb = new RenderTargetBitmap();
await rtb.RenderAsync(element);

IBuffer pixelBuffer = await rtb.GetPixelsAsync();
Debug.WriteLine($"Capacity = {pixelBuffer.Capacity}, Length={pixelBuffer.Length}");
byte[] pixels = pixelBuffer.ToArray();

我认为您的问题很可能发生在 ToArray 调用之前。我在我自己的 UWP 应用程序中使用完全相同的序列,得到如下调试输出:

Capacity = 216720, Length=216720

我在尝试在 UWP 应用程序中制作屏幕截图时遇到了同样的问题。

RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(uielement);

uielementWindow.Current.Content 时给了我这个例外。

但是当我尝试时

RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(null);

相同的代码毫无例外地工作,并为我提供了 UWP 应用程序的屏幕截图 window。