using Microsoft.Graphics.Canvas;
using System;
using System.Threading.Tasks;
using Windows.Graphics.DirectX;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Media.Imaging;
#nullable enable
namespace SampleApp.Views;
public static class CanvasDrawingSessionXamlExtensions
{
// DirectXPixelFormat https://learn.microsoft.com/en-us/uwp/api/windows.ui.xaml.media.imaging.rendertargetbitmap.getpixelsasync?view=winrt-26100
public static async Task DrawXamlUIAsync(this CanvasDrawingSession ds,
UIElement source,
int scaledWidth,
int scaledHeight,
RenderTargetBitmap? recycleRtb = null)
{
RenderTargetBitmap renderTargetBitmap = recycleRtb ?? new ();
await renderTargetBitmap.RenderAsync(source, scaledWidth, scaledHeight);
IBuffer buffer = await renderTargetBitmap.GetPixelsAsync();
using CanvasBitmap crt = CanvasBitmap.CreateFromBytes(
ds.Device,
buffer,
renderTargetBitmap.PixelWidth,
renderTargetBitmap.PixelHeight,
DirectXPixelFormat.B8G8R8A8UIntNormalized);
ds.DrawImage(crt);
}
}