Error using using RenderTargetBitmap in UWP

浪子不回头ぞ 提交于 2019-12-05 08:36:49

That method of extracting a pixel array is definitely applicable to UWP. As for the error, the decompiled ToArray() goes like this:

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

In other words, it calls the ToArray overload that takes a start index and a length:

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;
}

The line(s) almost certainly causing your problem:

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

...and since sourceIndex is necessarily 0, that would mean that source.Capacity is also 0.

I suggest you add some instrumentation to your code to inspect the 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();

I think it likely that your problem occurs before the ToArray call. I'm using the exact same sequence in my own UWP app, getting debug output like so:

Capacity = 216720, Length=216720

I've encountered the same problem when trying to make screenshot in UWP application.

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

gave me this exception when uielement is Window.Current.Content.

But when I tried

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

the same code worked with no exception and gives me the screenshot of UWP application window.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!