Qt 实现涂鸦板二:实现放大功能

在一的基础上改造:

.h 文件

#pragma once

#include <QtWidgets/QWidget>
#include "ui_xuexi.h"

#include "QMouseEvent"
#include "QKeyEvent"
#include "QPainter"
#include "QPushButton"

class xuexi : public QWidget
{
    Q_OBJECT

public:
    xuexi(QWidget *parent = Q_NULLPTR);

    void mousePressEvent(QMouseEvent*e);        // 按下
    void mouseMoveEvent(QMouseEvent*e);         // 移动
    void mouseReleaseRvent(QMouseEvent*e);      // 释放

    void paintEvent(QPaintEvent* );

public slots:
    void zoomIn();                              // 放大       

private:
    Ui::xuexiClass ui;

    QPixmap pix;
    QPoint lastPoint;
    QPoint endPoint;

    int scale;                                  // 放大倍数
    QPushButton* pushbutton;
};

 

 

.cpp 文件

#include "xuexi.h"

xuexi::xuexi(QWidget *parent)
    : QWidget(parent)
{
    ui.setupUi(this);

    resize(600, 500);
    pix = QPixmap(200, 200);
    pix.fill(Qt::white);

    scale = 1;
    pushbutton = new QPushButton("zoomIn", this);
    pushbutton->move(500, 450);
    connect(pushbutton, SIGNAL(clicked()), this, SLOT(zoomIn()));
}

void xuexi::mousePressEvent(QMouseEvent*e)
{
    if (e->button() == Qt::LeftButton)
    {
        lastPoint = e->pos();
    }
}

void xuexi::mouseMoveEvent(QMouseEvent*e)
{
    if (e->buttons() == Qt::LeftButton)
    {
        endPoint = e->pos();
        update();
    }
}

void xuexi::mouseReleaseRvent(QMouseEvent* e)
{
    if (e->button() == Qt::LeftButton)
    {
        endPoint = e->pos();
        update();
    }
}

void xuexi::paintEvent(QPaintEvent*)
{
    // 第一种:效果差点
    /*QPainter pp(&pix);
    pp.drawLine(lastPoint / scale, endPoint / scale);
    lastPoint = endPoint;

    QPainter painter(this);
    painter.scale(scale, scale);
    painter.drawPixmap(0, 0, pix);*/

    // 第二种:效果更好
    if (scale != 1)
    {
        QPixmap copyPix(pix.size() * scale);
        QPainter pter(&copyPix);
        pter.scale(scale, scale);
        pter.drawPixmap(0, 0, pix);
        pix = copyPix;
        scale = 1;
    }
    QPainter pp(&pix);
    pp.scale(scale, scale);
    pp.drawLine(lastPoint / scale, endPoint / scale);
    lastPoint = endPoint;

    QPainter painter(this);
    painter.drawPixmap(0, 0, pix);
}


void xuexi::zoomIn()
{
    scale *= 2;
    update();
}

 

 

这里的放大,写了两种实现方法:

方法一:将涂鸦后的图片放大,这样虽然可以实现,但是放大后,像素个数就表少了,画质就变差了,效果不是很好。

方法二:是将画布放大,这样像素个数不会变少,画质就高些,效果更好

 

posted @ 2021-11-04 23:02  十一的杂文录  阅读(413)  评论(0编辑  收藏  举报