0

我无法将 MS Chart(来自 WPF 工具包)导出到 PNG。我遵循不同论坛的步骤,但毕竟,我的 PNG 完全是黑色的。我究竟做错了什么?

private void export_graf_Click(object sender, RoutedEventArgs e)
        {
            if (mcChart.Series[0] == null)
            {
                MessageBox.Show("there is nothing to export");
            }
            else
            {

           RenderTargetBitmap renderBitmap = new RenderTargetBitmap((int)mcChart.ActualWidth,    (int)mcChart.ActualHeight, 95d, 95d, PixelFormats.Pbgra32);


                renderBitmap.Render(mcChart);

                Microsoft.Win32.SaveFileDialog uloz_obr = new Microsoft.Win32.SaveFileDialog();
                uloz_obr.FileName = "Graf";
                uloz_obr.DefaultExt = "png";


                Nullable<bool> result = uloz_obr.ShowDialog();
                if (result == true)
                {
                    string obr_cesta = uloz_obr.FileName; //cesta k souboru

              using (FileStream outStream = new FileStream(obr_cesta, FileMode.Create))
                    {
                        PngBitmapEncoder encoder = new PngBitmapEncoder();
                        encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
                        encoder.Save(outStream);
                    }

                }
4

1 回答 1

3

我认为您遇到了布局问题。该类RenderTargetBitmap在视觉层上工作,其中包括从其视觉父级继承的偏移和变换。将可视元素呈现为BitmapFrame. 您还可以指定背景颜色而不影响窗口的可视树,除非您想要透明背景。PNG 格式支持 alpha 透明度,一些图像查看器将透明像素显示为黑色。

WPF 的默认 dpi 是 96。我不知道您为什么指定 95。这不是零界限索引或类似的东西。下面的示例使用 96dpi。

private void export_graf_Click(object sender, RoutedEventArgs e)
{
    if (mcChart.Series[0] == null)
    {
        MessageBox.Show("there is nothing to export");
    }
    else
    {
        Rect bounds = VisualTreeHelper.GetDescendantBounds(mcChart);

        RenderTargetBitmap renderBitmap = new RenderTargetBitmap((int)bounds.Width, (int)bounds.Height, 96, 96, PixelFormats.Pbgra32);

        DrawingVisual isolatedVisual = new DrawingVisual();
        using (DrawingContext drawing = isolatedVisual.RenderOpen())
        {
            drawing.DrawRectangle(Brushes.White, null, new Rect(new Point(), bounds.Size)); // Optional Background
            drawing.DrawRectangle(new VisualBrush(mcChart), null, new Rect(new Point(), bounds.Size));
        }

        renderBitmap.Render(isolatedVisual);

        Microsoft.Win32.SaveFileDialog uloz_obr = new Microsoft.Win32.SaveFileDialog();
        uloz_obr.FileName = "Graf";
        uloz_obr.DefaultExt = "png";

        Nullable<bool> result = uloz_obr.ShowDialog();
        if (result == true)
        {
            string obr_cesta = uloz_obr.FileName;

            using (FileStream outStream = new FileStream(obr_cesta, FileMode.Create))
            {
                PngBitmapEncoder encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
                encoder.Save(outStream);
            }
        }
    }
}
于 2012-04-13T15:48:08.223 回答