您可以使用RenderTargetBitmap 类。创建一个扩展方法,它接受您要创建图像的任何UIElement(在这种情况下它将是您的页面)和一个文件,生成的图像将保存到该文件中。如果成功,该方法返回true:
public static async Task<bool> SaveVisualElementToFile(this UIElement element, StorageFile file)
{
try
{
var renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(element);
var pixels = await renderTargetBitmap.GetPixelsAsync();
using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);
byte[] bytes = pixels.ToArray();
encoder.SetPixelData(
BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Straight,
(uint)renderTargetBitmap.PixelWidth,
(uint)renderTargetBitmap.PixelHeight,
DisplayInformation.GetForCurrentView().LogicalDpi,
DisplayInformation.GetForCurrentView().LogicalDpi,
bytes);
await encoder.FlushAsync();
}
return true;
}
catch (Exception)
{
return false;
}
}
您需要确保您的UIElement 在可视化树中(已渲染),否则该方法将不起作用。
然后你可以这样调用方法:
StorageFolder localFolder = ApplicationData.Current.TemporaryFolder;
StorageFile file = await localFolder.CreateFileAsync(ShareSreenshotFileName, CreationCollisionOption.ReplaceExisting);
await view.SaveVisualElementToFile(file);
编辑:
出现您的问题是因为 ListView 已虚拟化,因此并非所有项目都已呈现。您可以使用StackPanel 作为列表视图的项目面板来禁用虚拟化:
<ListView>
<ListView.ItemsStackPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Vertical"/>
</ItemsPanelTemplate>
</ListView.ItemsStackPanel>
</ListView>
另一个问题是如果你传递listview的容器(网格或其他任何东西),生成的图像中只会显示容器边界,所以你需要将ListView引用传递给SaveVisualElementToFile方法。