Qt之图片的放大与缩小

时间:2024-04-01 16:05:14
#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QLabel>
#include <QDebug>
namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();
private:
    void resize_label();
private slots:
    void on_doubleSpinBox_h_valueChanged(double arg1);

    void on_doubleSpinBox_v_valueChanged(double arg1);

private:
    Ui::Widget *ui;
    QLabel label;
    QImage image;
    QImage original_image;
    QString path;
};

#endif // WIDGET_H
#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    path=QApplication::applicationDirPath()+"/1.png";
    qDebug()<<path;

    original_image=QImage(path);
    image=original_image;
    label.setPixmap(QPixmap::fromImage(image));

    label.show();
}

Widget::~Widget()
{
    delete ui;
}

void Widget::resize_label()
{
    QMatrix matrix;
    qDebug()<<"h:"<<ui->doubleSpinBox_h->value();
    matrix.scale(ui->doubleSpinBox_h->value(),ui->doubleSpinBox_v->value());
    image=original_image.transformed(matrix);
    label.setPixmap(QPixmap::fromImage(image));
    label.resize(image.size());
}

void Widget::on_doubleSpinBox_h_valueChanged(double arg1)
{
    resize_label();
}

void Widget::on_doubleSpinBox_v_valueChanged(double arg1)
{
    resize_label();
}

效果:

如何显示一张图片:

1.png--->QImage--->QPixmap--->QLabel

改变图片的水平大小和垂直大小,其实是在改变QImage。