从画布中保存的图像无法正确呈现 [英] Image being saved from canvas is not rendered properly
本文介绍了从画布中保存的图像无法正确呈现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图使用下面的代码来保存myCanvas的内容作为图像库中的图像文件(对于Windows Phone 8.1,而不是Silverlight)。当我运行应用程序,图像被保存,但它是扭曲的。我做错了什么?我已上传最终的图片和预期结果。
I'm trying to use the following code to save the contents of myCanvas as an image file in the gallery (for Windows Phone 8.1, not Silverlight). When I run the App, the image is saved but it is distorted. What am I doing wrong? I have uploaded the resultant image and the expected result.
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();
}
}
画布的XAML代码如下: p>
The XAML code for canvas is as follows:
<Canvas x:Name="myCanvas" Background="#FF33FFE3" Margin="25,75,26,10"
ManipulationStarted="myCanvas_ManipulationStarted"
ManipulationCompleted="myCanvas_ManipulationCompleted"
ManipulationDelta="myCanvas_ManipulationDelta" ManipulationMode="All"
Tapped="myCanvas_Tapped" MinHeight="555" MinWidth="350" Width="350" Height="555">
<Canvas.Clip>
<RectangleGeometry Rect="0 0 350 555"/>
</Canvas.Clip>
</Canvas>
推荐答案
参数 SetPixelData
方法不正确。
encoder.SetPixelData(BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Ignore,
(uint)element.Width, (uint)element.Height,
96, 96, bytes);
将它们更改为以下可以使其工作。
Change them to the follow can make it work.
encoder.SetPixelData(BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Ignore,
(uint)renderTargetBitmap.PixelWidth,
(uint)renderTargetBitmap.PixelHeight,
DisplayInformation.GetForCurrentView().LogicalDpi,
DisplayInformation.GetForCurrentView().LogicalDpi,
bytes);
您可以下载 XAML渲染到位图示例,以供参考。
You can download the XAML render to bitmap sample from MSDN for reference.
这篇关于从画布中保存的图像无法正确呈现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文