为什么来自网格的PNG文件会全黑?

时间:2019-04-07 20:23:11

标签: c# .net wpf

我正在尝试将WPF网格的PNG图像保存到文件中。网格在MainWindow上显示良好,但是创建的文件是完全黑色的(尽管尺寸很好)。

代码如下:

public MainWindow()
{
    InitializeComponent();    
    int length = 30;

    //Create Grid:
    Grid myGrid = new Grid
    {
        Width = length,
        Height = length,
        Background = Brushes.Aqua,
    };

    //Save to file:
    RenderTargetBitmap bmp = new RenderTargetBitmap(length, length, 96, 96, PixelFormats.Pbgra32);
    bmp.Render(myGrid);
    PngBitmapEncoder encoder = new PngBitmapEncoder();
    encoder.Frames.Add(BitmapFrame.Create(bmp));
    FileStream fileStream = new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\test.png", FileMode.Create);
    encoder.Save(fileStream);

    //Show on Window: (shows fine.)
    gridOnMainWindow.Children.Add(myGrid);
}

1 个答案:

答案 0 :(得分:1)

使用RenderTargetBitmap之类的工具时,您必须参与WPF布局过程的Measure / Arrange周期。参见MSDN > WPF > Advanced > Layout > Measuring and Arranging Children

将示例更改为:

int length = 30;

//Create Grid:
Grid myGrid = new Grid
{
    Width = length,
    Height = length,
    Background = Brushes.Aqua,
};
myGrid.Measure(new Size(length, length));
myGrid.Arrange(new Rect(0, 0, length, length));

//Save to file:
RenderTargetBitmap bmp = new RenderTargetBitmap(length, length, 96, 96, PixelFormats.Pbgra32);
bmp.Render(myGrid);
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bmp));
using (var fileStream = File.OpenWrite("test.png"))
{
    encoder.Save(fileStream);
}

产生预期的图像:

Cyan