You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

OxyPlot图表导出为PNG问题求助(附Chart.xaml代码片段)

解决OxyPlot图表导出为PNG的方案

我来帮你搞定OxyPlot图表导出为PNG的需求,结合你给出的XAML片段,咱们可以分两步实现:先完善XAML布局,再编写后台导出逻辑。

第一步:完善你的Chart.xaml代码

首先给Plot控件加个名字,方便后台代码引用,再添个导出按钮触发操作:

<Window x:Class="P1.Chart"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:oxy="http://oxyplot.org/wpf"
        xmlns:local="clr-namespace:P1"
        Title="Example 1 (WPF)" Height="800" Width="800"
        DataContext="{Binding RelativeSource={RelativeSource Self}}">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <!-- 给Plot控件命名,后台要用到 -->
        <oxy:Plot x:Name="MyOxyPlot" Grid.Row="0">
            <oxy:Plot.Axes>
                <oxy:LinearAxis Position="Bottom" Minimum="-20" Maximum="20"/>
                <!-- 这里补充你原本的其他轴、系列代码 -->
            </oxy:Plot.Axes>
            <!-- 你的图表数据系列,比如LineSeries、BarSeries等 -->
        </oxy:Plot>
        <!-- 导出按钮 -->
        <Button Grid.Row="1" Content="导出为PNG" Margin="10" Click="ExportToPng_Click"/>
    </Grid>
</Window>

第二步:编写后台导出逻辑

在Chart.xaml.cs里实现按钮点击事件,用OxyPlot自带的PngExporter来完成导出:

using System.Windows;
using Microsoft.Win32;
using OxyPlot.Wpf;

namespace P1
{
    public partial class Chart : Window
    {
        public Chart()
        {
            InitializeComponent();
            // 这里初始化你的图表数据,比如给MyOxyPlot.Model添加系列
        }

        private void ExportToPng_Click(object sender, RoutedEventArgs e)
        {
            // 弹出保存文件对话框
            var saveDialog = new SaveFileDialog
            {
                Filter = "PNG图片|*.png",
                Title = "导出OxyPlot图表",
                FileName = "我的OxyPlot图表"
            };

            if (saveDialog.ShowDialog() == true)
            {
                // 配置导出参数
                var pngExporter = new PngExporter
                {
                    // 用图表实际尺寸,也可以手动设固定值比如800、600
                    Width = (int)MyOxyPlot.ActualWidth,
                    Height = (int)MyOxyPlot.ActualHeight,
                    // 分辨率,默认96,高清可以设192
                    Resolution = 96
                };

                // 执行导出
                pngExporter.Export(MyOxyPlot.Model, saveDialog.FileName);
                MessageBox.Show("图表导出成功啦!", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }
    }
}

几个关键注意点

  • 确保你的项目已经安装了OxyPlot.Wpf NuGet包,版本要和.NET框架匹配
  • 如果导出的图片显示不全,试试手动指定Width和Height(比如Width=800),而不是依赖ActualWidth
  • 想要高清图就把Resolution调大,比如192,导出的图片会更清晰但文件体积也会变大
  • 一定要保证MyOxyPlot.Model已经正确初始化并绑定了数据,不然导出的会是空图

内容的提问来源于stack exchange,提问作者Danki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:22:46