使用 RenderTargetBitmap 將控制元件渲染為影象

<TextBlock x:Name="MyControl"
           Text="Hello, world!" />
var rtb = new RenderTargetBitmap();
await rtb.RenderAsync(MyControl); // Render control to RenderTargetBitmap

// Get pixels from RTB
IBuffer pixelBuffer = await rtb.GetPixelsAsync();
byte[] pixels = pixelBuffer.ToArray();

// Support custom DPI
DisplayInformation displayInformation = DisplayInformation.GetForCurrentView();

var stream = new InMemoryRandomAccessStream();
BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);
encoder.SetPixelData(BitmapPixelFormat.Bgra8, // RGB with alpha
                     BitmapAlphaMode.Premultiplied,
                     (uint)rtb.PixelWidth,
                     (uint)rtb.PixelHeight,
                     displayInformation.RawDpiX,
                     displayInformation.RawDpiY,
                     pixels);

await encoder.FlushAsync(); // Write data to the stream
stream.Seek(0); // Set cursor to the beginning

// Use stream (e.g. save to file)