其他分享
首页 > 其他分享> > 从画布保存的图像无法正确渲染

从画布保存的图像无法正确渲染

作者:互联网

我正在尝试使用以下代码将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();
    }
}

画布的XAML代码如下:

<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);

将它们更改为以下内容可以使其正常工作.

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

您可以从MSDN下载XAML render to bitmap sample以供参考.

标签:windows-rt,image,canvas,windows-phone-8-1,c
来源: https://codeday.me/bug/20191120/2044433.html