将 UI 元素渲染到图像

public static async Task<WriteableBitmap> RenderUIElement(UIElement element)
{
    var bitmap = new RenderTargetBitmap();
    await bitmap.RenderAsync(element);   
    var pixelBuffer = await bitmap.GetPixelsAsync();
    var pixels = pixelBuffer.ToArray();
    var writeableBitmap = new WriteableBitmap(bitmap.PixelWidth, bitmap.PixelHeight);
    using (Stream stream = writeableBitmap.PixelBuffer.AsStream())
    {
        await stream.WriteAsync(pixels, 0, pixels.Length);
    }
    return writeableBitmap;
}

由于 WriteableBitmapImageSource,你可以使用它来设置 Image 控件的 Source 属性,无论是绑定还是代码隐藏