从canvas保存的图像无法正确呈现

我正在尝试使用以下代码将myCanvas的内容保存为库中的图像文件(对于Windows Phone 8.1,而不是Silverlight)。 当我运行应用程序时,图像被保存但是它被扭曲了。 我究竟做错了什么? 我上传了结果图像和预期结果。

在此处输入图像描述

public async void SaveFileToPhone() { var file = await KnownFolders.PicturesLibrary.CreateFileAsync("bug.png", CreationCollisionOption.GenerateUniqueName); await SaveVisualElementToFile(myCanvas, file); } async Task SaveVisualElementToFile(FrameworkElement element, StorageFile file) { var renderTargetBitmap = new RenderTargetBitmap(); await renderTargetBitmap.RenderAsync(element, (int)element.Width, (int)element.Height); var pixels = await renderTargetBitmap.GetPixelsAsync(); txt_bug.Text = "Width: " + (int)element.Width + " Height:" + (int)element.Height; 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.Ignore, (uint)element.Width, (uint)element.Height, 96, 96, bytes); await encoder.FlushAsync(); } } 

canvas的XAML代码如下:

      

SetPixelData方法的参数不正确。

 encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)element.Width, (uint)element.Height, 96, 96, bytes); 

将它们更改为以下可以使其工作。

 encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)renderTargetBitmap.PixelWidth, (uint)renderTargetBitmap.PixelHeight, DisplayInformation.GetForCurrentView().LogicalDpi, DisplayInformation.GetForCurrentView().LogicalDpi, bytes); 

您可以从MSDN下载XAML渲染到位图示例以供参考。