【发布时间】:2018-05-28 16:11:28
【问题描述】:
我试图将 UWP 中的画布转换为图像 (RenderTargetBitmap)。我有两个选项可以将图像返回给最终用户。
StorageFileSystem.IO.Stream
当我使用存储文件时,一切都按预期工作。 但是当我使用内存流时,应用程序会挂起。我创建了一个简单的示例来重现该问题。
<Grid Background="White" Name ="Main_Grid">
<Button Content="UIToImage" Margin="141,159,0,0" VerticalAlignment="Top" Click="UIToImageAsync"></Button>
</Grid>
private async void UIToImageAsync(object sender, RoutedEventArgs e)
{
//Pick a folder
var folder = KnownFolders.PicturesLibrary;
var storageFile = await folder.CreateFileAsync("Output.png", CreationCollisionOption.ReplaceExisting);
//using (var inputImgStream = await storageFile.OpenStreamForWriteAsync())//this works
using (var inputImgStream = new MemoryStream())//this doesn't work
{
//Draw a line
Windows.UI.Xaml.Shapes.Path path = new Windows.UI.Xaml.Shapes.Path();
DrawShape(path);
//The canvas to hold the above shape - line
var canvas = new Canvas();
//Add canvas to the grid in XAML
Main_Grid.Children.Add(canvas);
canvas.Children.Add(path);
//Draw the canvas to the image
RenderTargetBitmap bitmap = null;
await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
bitmap = new RenderTargetBitmap();
canvas.Height = 800;
canvas.Width = 1380;
canvas.RenderTransform = new TranslateTransform { X = 1, Y = 100
};
});
//Render a bitmap image
await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,async () =>
{
await bitmap.RenderAsync(canvas, 1380, 800);
});
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, inputImgStream.AsRandomAccessStream());// I suspect passing the MemoryStream is the issue. While 'StorageFile' is used there are no issues.
IBuffer pixelBuffer = await bitmap.GetPixelsAsync();
encoder.SetPixelData(
BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Ignore,
(uint)bitmap.PixelWidth,
(uint)bitmap.PixelHeight,
DisplayInformation.GetForCurrentView().LogicalDpi,
DisplayInformation.GetForCurrentView().LogicalDpi,
pixelBuffer.ToArray());
await encoder.FlushAsync(); // The application hangs here
}
}
private void DrawShape(Windows.UI.Xaml.Shapes.Path path)
{
PathGeometry lineGeometry = new PathGeometry();
PathFigure lineFigure = new PathFigure();
LineSegment lineSegment = new LineSegment();
lineFigure.StartPoint = new Point(100, 100);
lineSegment.Point = new Point(200, 200);
lineFigure.Segments.Add(lineSegment);
path.Data = lineGeometry;
SolidColorBrush strokeBrush = new SolidColorBrush(Windows.UI.Color.FromArgb(255, 255, 0, 0));
path.Stroke = strokeBrush;
path.StrokeThickness = 5;
lineGeometry.Figures.Add(lineFigure);
}
谁能指出造成这种情况的原因?
【问题讨论】: