Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <QApplication>
- #include <QMainWindow>
- #include <QGraphicsScene>
- #include <QGraphicsView>
- #include <QGraphicsLineItem>
- #include <QPointF>
- #include <cmath>
- // Функція для обертання точки навколо іншої точки на певний кут
- QPointF rotatePoint(const QPointF& center, const QPointF& point, qreal angle) {
- qreal s = sin(angle * M_PI / 180);
- qreal c = cos(angle * M_PI / 180);
- qreal x = point.x() - center.x();
- qreal y = point.y() - center.y();
- qreal new_x = x * c - y * s;
- qreal new_y = x * s + y * c;
- new_x += center.x();
- new_y += center.y();
- return QPointF(new_x, new_y);
- }
- // Функція для малювання фрактала Коха
- void drawKochFractal(QGraphicsScene* scene, QPointF p1, QPointF p2, int depth, int ratio) {
- if (depth == 0) {
- scene->addLine(QLineF(p1, p2));
- } else {
- QPointF p3 = p1 + (p2 - p1) / ratio;
- QPointF p4 = p1 + (p2 - p1) / ratio * 2;
- QPointF p5 = rotatePoint(p3, p4, 60);
- drawKochFractal(scene, p1, p3, depth - 1, ratio);
- drawKochFractal(scene, p3, p5, depth - 1, ratio);
- drawKochFractal(scene, p5, p4, depth - 1, ratio);
- drawKochFractal(scene, p4, p2, depth - 1, ratio);
- }
- }
- int main(int argc, char *argv[]) {
- QApplication app(argc, argv);
- QMainWindow mainWindow;
- QGraphicsScene scene;
- QGraphicsView view(&scene);
- mainWindow.setCentralWidget(&view);
- mainWindow.show();
- // Початкові точки квадрата
- QPointF p1(100, 100);
- QPointF p2(300, 100);
- QPointF p3(300, 300);
- QPointF p4(100, 300);
- int iter = 4;
- int ratio = 4;
- // Рекурсивно малюємо фрактал Коха
- drawKochFractal(&scene, p1, p2, iter, ratio);
- drawKochFractal(&scene, p2, p3, iter, ratio);
- drawKochFractal(&scene, p3, p4, iter, ratio);
- drawKochFractal(&scene, p4, p1, iter, ratio);
- return app.exec();
- }
Advertisement
Add Comment
Please, Sign In to add comment