Skip to content

Instantly share code, notes, and snippets.

@Cheesebaron
Created August 25, 2015 08:40
Show Gist options
  • Save Cheesebaron/51e0d5afb5d3ff648f89 to your computer and use it in GitHub Desktop.
Save Cheesebaron/51e0d5afb5d3ff648f89 to your computer and use it in GitHub Desktop.
Capture UI elements Windows
protected async Task<RenderTargetBitmap> CaptureUiElementToStreamAsync(FrameworkElement uiElement,
IRandomAccessStream stream)
{
return await CaptureUiElementToStreamAsync(uiElement, stream, BitmapEncoder.PngEncoderId);
}
private async Task<RenderTargetBitmap> CaptureUiElementToStreamAsync(FrameworkElement uiElement,
IRandomAccessStream stream, Guid encoderId)
{
if (uiElement == null) throw new ArgumentNullException(nameof(uiElement));
if (stream == null) throw new ArgumentNullException(nameof(stream));
if (BitmapEncoder.GetEncoderInformationEnumerator().All(id => id.CodecId != encoderId))
throw new ArgumentException("Unknown encoder id", nameof(encoderId));
try
{
var renderTagetBitmap = new RenderTargetBitmap();
await renderTagetBitmap.RenderAsync(uiElement);
var pixels = await renderTagetBitmap.GetPixelsAsync();
var logicalDpi = DisplayInformation.GetForCurrentView().LogicalDpi;
var encoder = await BitmapEncoder.CreateAsync(encoderId, stream);
encoder.SetPixelData(BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Ignore,
(uint) renderTagetBitmap.PixelWidth,
(uint) renderTagetBitmap.PixelHeight,
logicalDpi,
logicalDpi,
pixels.ToArray());
await encoder.FlushAsync();
return renderTagetBitmap;
}
catch (Exception e)
{
Mvx.TaggedTrace("BaseView:CaptureUiElementToStreamAsync()", "Failed with exception:\n{0}", e);
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment