4

I search in web but I not found any solution to take a screenshot an UI element (in bitmap by example) in UWP - Universal Windows Platform.

demonplus
  • 5,613
  • 12
  • 49
  • 68
fipcurren88
  • 701
  • 5
  • 26
  • Here is a official [XAML render to bitmap sample](https://code.msdn.microsoft.com/windowsapps/XAML-render-to-bitmap-dd4f549f), you can have a check. Although this sample is for Windows 8.1 Store app, but in UWP the implement is the same. – Jay Zuo Mar 17 '16 at 08:55
  • Isn't this what you want: https://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.media.imaging.rendertargetbitmap?f=255&MSPPError=-2147217396 – WiredPrairie Mar 17 '16 at 10:44
  • @JayZuo-MSFT, Thanks. But object to return type of RenderTargetBitmap, but I need this image(screenshot) in bitmap format, because I really need to do args.DragUI.SetContentFromBitmapImage(myBitmap); on DragStarting of an UI Element. Thanks – fipcurren88 Mar 17 '16 at 15:12
  • `RenderTargetBItmap` can be converted to bitmap using `BitmapEncoder` – Irwene Mar 17 '16 at 15:22
  • @Sidewinder94, Thanks. In short, I cant capture image from UI Element and convert to BitmapImage? Ty – fipcurren88 Mar 17 '16 at 15:30

1 Answers1

3

You may use Render XAML to bitmap Some Sample Code here:

    // Render to an image at the current system scale and retrieve pixel contents
    RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
    await renderTargetBitmap.RenderAsync(RenderedGrid);
    var pixelBuffer = await renderTargetBitmap.GetPixelsAsync();

    var savePicker = new FileSavePicker();
    savePicker.DefaultFileExtension = ".png";
    savePicker.FileTypeChoices.Add(".png", new List<string> { ".png" });
    savePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
    savePicker.SuggestedFileName = "snapshot.png";

    // Prompt the user to select a file
    var saveFile = await savePicker.PickSaveFileAsync();

    // Verify the user selected a file
    if (saveFile == null)
        return;

    // Encode the image to the selected file on disk
    using (var fileStream = await saveFile.OpenAsync(FileAccessMode.ReadWrite))
    {
        var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fileStream);

        encoder.SetPixelData(
            BitmapPixelFormat.Bgra8,
            BitmapAlphaMode.Ignore,
            (uint)renderTargetBitmap.PixelWidth,
            (uint)renderTargetBitmap.PixelHeight,
            DisplayInformation.GetForCurrentView().LogicalDpi,
            DisplayInformation.GetForCurrentView().LogicalDpi,
            pixelBuffer.ToArray());

        await encoder.FlushAsync();
    }

Sample Example https://code.msdn.microsoft.com/windowsapps/XAML-render-to-bitmap-dd4f549f

Dev-Systematix
  • 439
  • 6
  • 26