我正在开发一个 UWP 应用程序,它有一个带有子项、图像和文本块的网格。我有两件事想要实现并需要帮助。
如何使用预定义名称将 Grid 元素及其子内容作为图像(最好是 PNG)保存在本地文件夹中?
如何检索此保存的图像,然后将其作为附件与其他兼容的应用程序共享?
Example:
<StackPanel Orientation="Vertical">
<Grid Name="myGrid"
HorizontalAlignment="Stretch"
Background="Black">
<Image Name="myImage"
Source="Assets/image1.png"
Stretch="Uniform"/>
<TextBlock Name="myTextBlock"
HorizontalAlignment="Center"
VerticalAlignment="Center"
TextWrapping="Wrap"
Text="Sample user text"/>
</Grid>
<Button Name="saveButton"
Content="Save"
Margin="10,10,0,0"
Click="saveButton_Click" />
<Button Name="shareButton"
Content="Share"
Margin="10,10,0,0"
Click="shareButton_Click" />
</StackPanel>
编辑:在 saveButton_Click 事件中尝试了这段代码。似乎不起作用。
RenderTargetBitmap rtb = new RenderTargetBitmap();
await rtb.RenderAsync(myGrid);
var pixelBuffer = await rtb.GetPixelsAsync();
var pixels = pixelBuffer.ToArray();
var displayInformation = DisplayInformation.GetForCurrentView();
var stream = new InMemoryRandomAccessStream();
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);
encoder.SetPixelData(BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Premultiplied,
(uint)rtb.PixelWidth,
(uint)rtb.PixelHeight,
displayInformation.RawDpiX,
displayInformation.RawDpiY,
pixels);
await encoder.FlushAsync();
stream.Seek(0);
FileStream filestream = File.Create("C:\\Users\\pcUser\\Desktop\\testimage.png", (int)stream.Size);
EDIT2:尝试了这段代码。它似乎有点工作,但我只得到一个黑色图像,这可能是因为它只保存 myGrid,而不是儿童内容。
RenderTargetBitmap rtb = new RenderTargetBitmap();
await rtb.RenderAsync(quoteGrid);
var pixelBuffer = await rtb.GetPixelsAsync();
var pixels = pixelBuffer.ToArray();
var displayInformation = DisplayInformation.GetForCurrentView();
var stream = new InMemoryRandomAccessStream();
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);
encoder.SetPixelData(BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Premultiplied,
(uint)rtb.PixelWidth,
(uint)rtb.PixelHeight,
displayInformation.RawDpiX,
displayInformation.RawDpiY,
pixels);
await encoder.FlushAsync();
stream.Seek(0);
var wbm = new WriteableBitmap(rtb.PixelWidth, rtb.PixelHeight);
await wbm.SetSourceAsync(stream);
StorageFolder folder = ApplicationData.Current.LocalFolder;
if (folder != null)
{
StorageFile file = await folder.CreateFileAsync("testImage" + ".png", CreationCollisionOption.ReplaceExisting);
using (var storageStream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, storageStream);
var pixelStream = wbm.PixelBuffer.AsStream();
await pixelStream.ReadAsync(pixels, 0, pixels.Length);
encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied, (uint)wbm.PixelWidth, (uint)wbm.PixelHeight, displayInformation.RawDpiX, displayInformation.RawDpiY, new byte[pixelStream.Length]);
await encoder.FlushAsync();
}
}