c++ 画数学函数图
c++ 画数学函数图并不像 python 方便。
- 最好可以使用 matplotlib-cpp,这个将 python 的 matplotlib 库转到 c++ 里了,语法跟 python 变动不大。但是,我在 mac clion 上始终没有安装成功,总是出错,看了 matplotlib-cpp github 主页说明,似乎还是基于 python 2.7,其他的维护更新似乎也没那么及时。
- 还有一个画图的库 JKQtPlotter,这个基于 Qt,但是安装库也是各种错误,始终没有成功。github 主页的介绍非常晦涩,我始终没看明白这个库的 cmake 到底要怎么配置。但是,若将这个库下载下来,直接以项目的形式打开,里面的例子能够正确运行。但还是不方便,我只想调用这个库,并不想每次都在你这个库里新建项目。
- 最后找到了 qt 自带的 QPainter,这个就方便多了。qt 是 c++ 使用非常广的开发图形库,非常容易配置 cmake。而且,对于画一些数学函数图,基本够用了。初步使用起来类似 java 的 JFrame。
下面是 QPinter 生成的一个简单的正弦函数线图:
#include <QApplication>
#include <QWidget>
#include <QPainter>
#include <cmath>
class FunctionPlotter : public QWidget {
protected:
void paintEvent(QPaintEvent *) override {
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
// 坐标轴
painter.setPen(Qt::black);
// 两个点坐标之间的连线
painter.drawLine(20, height() / 2, width() - 20, height() / 2); // X轴
painter.drawLine(width() / 2, 20, width() / 2, height() - 20); // Y轴
// 画函数 y = sin(x)
painter.setPen(Qt::red);
for (int x = -width() / 2; x < width() / 2; x++) {
int y1 = -std::sin(x / 50.0) * 100; // 归一化
int y2 = -std::sin((x + 1) / 50.0) * 100;
painter.drawLine(width() / 2 + x, height() / 2 + y1,
width() / 2 + x + 1, height() / 2 + y2);
}
}
};
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
FunctionPlotter plotter;
plotter.resize(600, 400);
plotter.setWindowTitle("数学函数绘制");
plotter.show();
return app.exec();
}
没有保存图片的功能,但可以直接用电脑截图保存,也可以用 QPainter 里面一些保存图片的函数。