这种提取像素阵列的方法绝对适用于 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