Skip to main content
标签ad报错:该广告ID(9)不存在。
  主页 > Qt入门

一个qt/c++ demo,用于显示 Triflake(三叶雪花) 分形图

2023-04-24 浏览:
标签ad报错:该广告ID(7)不存在。

#include <QApplication>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QVector>
#include <QPointF>
#include <QPen>

// 递归生成 Triflake 的点集
void generateTriflake(QGraphicsScene &scene, const QPointF &origin, double angle, double length, int depth)
{
    if (depth == 0) {
        return;
    }

    // 计算下一个点的位置和角度
    double angle1 = angle;
    double angle2 = angle - M_PI / 3.0;
    double angle3 = angle + M_PI / 3.0;
    double x1 = origin.x() + length * qCos(angle1);
    double y1 = origin.y() + length * qSin(angle1);
    double x2 = origin.x() + length * qCos(angle2);
    double y2 = origin.y() + length * qSin(angle2);
    double x3 = origin.x() + length * qCos(angle3);
    double y3 = origin.y() + length * qSin(angle3);

    // 添加直线
    QPen pen;
    pen.setColor(Qt::GlobalColor::red);
    scene.addLine(origin.x(), origin.y(), x1, y1, pen);
    scene.addLine(x1, y1, x2, y2, pen);
    scene.addLine(x2, y2, x3, y3, pen);
    scene.addLine(x3, y3, origin.x(), origin.y(), pen);

    // 递归生成子雪花
    generateTriflake(scene, QPointF((origin.x() + x1) / 2.0, (origin.y() + y1) / 2.0), angle1, length / 3.0, depth - 1);
    generateTriflake(scene, QPointF((x1 + x2) / 2.0, (y1 + y2) / 2.0), angle2, length / 3.0, depth - 1);
    generateTriflake(scene, QPointF((x2 + x3) / 2.0, (y2 + y3) / 2.0), angle3, length / 3.0, depth - 1);
    generateTriflake(scene, QPointF((x3 + origin.x()) / 2.0, (y3 + origin.y()) / 2.0), angle, length / 3.0, depth - 1);
}

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QGraphicsScene scene;
    QGraphicsView view(&scene);

    generateTriflake(scene, QPointF(300, 300), 0.0, 200.0, 4); // 生成 Triflake

    view.show();

    return app.exec();
}

参考数学公式