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

一个qt/c++ demo,用于显示 Lévy C Curve(莱维C曲线) 分形图

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

#include <QApplication>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QPointF>
#include <QtMath>

// Lévy C Curve 的绘制函数
void drawLevyCCurve(QGraphicsScene *scene, const QPointF &start, const QPointF &end, int depth)
{
    // 计算两点之间的距离
    qreal distance = std::sqrt(qPow(end.x() - start.x(), 2.0) + qPow(end.y() - start.y(), 2.0));

    if (distance < 5 || depth <= 0) {  // 递归终止条件
        scene->addLine(start.x(), start.y(), end.x(), end.y());
    } else {
        // 计算旋转角度及中点坐标
        qreal angle = qDegreesToRadians(45);
        qreal cosAngle = std::cos(angle);
        qreal sinAngle = std::sin(angle);
        QPointF midPoint((start.x() + end.x()) / 2.0, (start.y() + end.y()) / 2.0);

        // 递归绘制左半段
        QPointF leftEnd(midPoint.x() + cosAngle * distance / 2.0, midPoint.y() + sinAngle * distance / 2.0);
        drawLevyCCurve(scene, start, leftEnd, depth - 1);

        // 递归绘制右半段
        QPointF rightEnd(midPoint.x() - cosAngle * distance / 2.0, midPoint.y() - sinAngle * distance / 2.0);
        drawLevyCCurve(scene, rightEnd, end, depth - 1);
    }
}

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

    QGraphicsScene scene;
    QGraphicsView view(&scene);

    const int depth = 12;
    QPointF start(50, 100);
    QPointF end(550, 100);
    drawLevyCCurve(&scene, start, end, depth);

    view.show();
    return app.exec();
}