1.简介
在一些游戏中看见类似解密破案的效果,使用手触摸去擦拭图片上的灰尘,然后显示最终的图片,所以也想试试Qt实现的效果。大家有自己想做的效果,都可以尝试。
以下是效果展示图。
可以控制橡皮擦的大小,进行擦拭。
2.原理
鼠标按住,然后移动,不断的给移动的圆形区域设置像素点的值,显示图片。
源码:
#include "wipewidget.h"
#include "ui_wipewidget.h"
#include <QDebug>WipeWidget::WipeWidget(QWidget *parent) :QWidget(parent),ui(new Ui::WipeWidget)
{ui->setupUi(this);setMouseTracking(true);
}WipeWidget::~WipeWidget()
{delete ui;
}void WipeWidget::setEraserSize(int size)
{m_eraserSize = size;m_point = QPoint(this->width()/2,this->height()/2);update();
}void WipeWidget::paintEvent(QPaintEvent *e)
{Q_UNUSED(e);//画圆圈QPainter painter(this);painter.setRenderHint(QPainter::Antialiasing, true); // 启用抗锯齿painter.drawImage(0,0,m_image);QPen pen;pen.setWidth(2);pen.setColor(Qt::white);painter.setPen(pen);qDebug()<<"";painter.drawEllipse(m_point,m_eraserSize,m_eraserSize);if(m_isMousePressed)setImage(m_point);
}void WipeWidget::mousePressEvent(QMouseEvent *event)
{m_isMousePressed = true;
}void WipeWidget::mouseReleaseEvent(QMouseEvent *event)
{Q_UNUSED(event);m_isMousePressed = false;
}void WipeWidget::mouseMoveEvent(QMouseEvent *event)
{m_point = event->pos();update();
}void WipeWidget::showEvent(QShowEvent *event)
{Q_UNUSED(event);if(m_isInit)return;m_isInit = true;m_srcImage = QImage("./demo.jpeg").scaled(this->width(),this->height());m_image = QImage(m_srcImage.width(),m_srcImage.height(),m_srcImage.format());
}void WipeWidget::setImage(QPoint point)
{int centerX = point.x();int centerY = point.y();if(centerX > m_srcImage.width() ||centerY > m_srcImage.height())return;int radius = m_eraserSize;for (int x = qMax(centerX - radius,0);x < qMin(centerX + radius,m_srcImage.width()); x++){for (int y = qMax(centerY - radius,0);y < qMin(centerY + radius,m_srcImage.height()); y++){if ((x - centerX) * (x - centerX) + (y - centerY) * (y - centerY) <= radius * radius){if(x <= m_srcImage.width() && m_srcImage.height()-y <= m_srcImage.height()){m_image.setPixel(x,y,m_srcImage.pixel(x, y));}}}}
}
3.完整工程
https://download.csdn.net/download/wzz953200463/88906763
4.相关推荐
1.圆形进度条实现
2.麦克风音量大小模拟
3.自定义时钟
4.自定义长条进度条