Created
August 25, 2015 08:40
-
-
Save Cheesebaron/51e0d5afb5d3ff648f89 to your computer and use it in GitHub Desktop.
Capture UI elements Windows
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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