將 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;
}
由於 WriteableBitmap
是 ImageSource
,你可以使用它來設定 Image 控制元件的 Source 屬性,無論是繫結還是程式碼隱藏