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

一个qt/c++ demo,用于显示 Hexagonal Gasket(六角镂垫) 分形图

2023-04-24 浏览:
标签ad报错:该广告ID(7)不存在。
#include <QApplication>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QVector>
#include <QPolygonF>

// 将六边形的一条边转换为菱形
QVector<QPointF> transformEdge(const QPointF &start, const QPointF &end)
{
   QVector<QPointF> points(4);
   QPointF center = (start + end) / 2.0;
   QPointF dir = (end - start) / 2.0;
   QPointF normal(dir.y(), -dir.x());

   points[0] = center + dir;
   points[1] = center + normal;
   points[2] = center - dir;
   points[3] = center - normal;

   return points;
}

// 生成六角镂垫的多边形集
void generateHexagonalGasket(QVector<QPolygonF> &polygons, const QPolygonF &polygon, int depth)
{
   if (depth == 0) {  // 递归终止条件
       return;
   }

   // 将当前多边形的每条边转换为菱形并添加到多边形集中
   for (int i = 0; i < polygon.size(); ++i) {
       const QPointF &start = polygon[i];
       const QPointF &end = polygon[(i+1)%polygon.size()];
       const QVector<QPointF> &diamond = transformEdge(start, end);
       QPolygonF newPolygon;
       newPolygon << diamond[0] << diamond[1] << diamond[2] << diamond[3] << diamond[0];
       polygons.append(newPolygon);

       // 递归生成子多边形
       generateHexagonalGasket(polygons, newPolygon, depth - 1);
   }
}

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

   QGraphicsScene scene;
   QGraphicsView view(&scene);

   QPolygonF polygon;
   polygon << QPointF(400.0, 50.0) << QPointF(550.0, 200.0)
           << QPointF(550.0, 350.0) << QPointF(400.0, 500.0)
           << QPointF(250.0, 350.0) << QPointF(250.0, 200.0)
           << QPointF(400.0, 50.0);

   QVector<QPolygonF> polygons;
   polygons.append(polygon);
   generateHexagonalGasket(polygons, polygon, 3);

   // 将多边形添加到场景中
   for (const auto &poly : polygons) {
       scene.addPolygon(poly);
   }

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