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

一个qt/c++ demo,用于显示 Burning Ship Fractal(沉船分形) 分形图

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

#include <QtWidgets>
#include <QPainter>

class BurningShip : public QWidget {
public:
    BurningShip(QWidget *parent = nullptr) : QWidget(parent) {

        QPixmap pixmap("https://upload.wikimedia.org/wikipedia/commons/thumb/7/72/Burning_ship_fractal_zoom_e-126.png/220px-Burning_ship_fractal_zoom_e-126.png");

        setFixedSize(600, 600);
        setWindowTitle("Burning Ship Fractal(沉船分形)");

        image = QImage(size(), QImage::Format_RGB32);
        image.fill(Qt::white);

        drawBurningShip();

        label = new QLabel(this);
        label->setPixmap(pixmap.scaledToWidth(400));
        label->move(100, 450);
    }

private:
    QImage image;
    QLabel* label;

    void drawBurningShip() {
        double min_x = -1.8;
        double max_x = -1.5;
        double min_y = -0.1;
        double max_y = 0.2;

        int width = image.width();
        int height = image.height();

        double x_step = (max_x - min_x) / width;
        double y_step = (max_y - min_y) / height;

        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                double c_real = min_x + x * x_step;
                double c_imag = min_y + y * y_step;

                double z_real = c_real;
                double z_imag = c_imag;

                int iterations = 0;
                while (z_real * z_real + z_imag * z_imag <= 4 && iterations < 255) {
                    double z_real_new = z_real * z_real - z_imag * z_imag + c_real;
                    double z_imag_new = 2 * fabs(z_real * z_imag) + c_imag;
                    z_real = z_real_new;
                    z_imag = z_imag_new;
                    iterations++;
                }

                image.setPixel(x, y, qRgb(iterations, iterations, iterations));
            }
        }
    }

    void paintEvent(QPaintEvent* /* event */) {
        QPainter painter(this);

        painter.drawImage(0, 0, image);

        painter.end();
    }
};

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

    BurningShip window;
    window.show();

    return app.exec();
}