好的,以下是一个基于Qt的完整示例,演示了如何在白板软件中实现橡皮擦功能:
#include <QApplication>
#include <QWidget>
#include <QPainter>
#include <QMouseEvent>
class Whiteboard : public QWidget
{
public:
Whiteboard(QWidget* parent = nullptr)
: QWidget(parent), m_eraserSize(10), m_drawing(false)
{
setAttribute(Qt::WA_StaticContents);
}
protected:
void mousePressEvent(QMouseEvent* event) override
{
if (event->button() == Qt::LeftButton) {
m_lastPos = event->pos();
m_drawing = true;
}
}
void mouseMoveEvent(QMouseEvent* event) override
{
if ((event->buttons() & Qt::LeftButton) && m_drawing) {
QPainter painter(&m_image);
painter.setPen(Qt::white);
painter.setBrush(Qt::white);
painter.drawEllipse(event->pos(), m_eraserSize, m_eraserSize);
update();
}
}
void mouseReleaseEvent(QMouseEvent* event) override
{
if (event->button() == Qt::LeftButton && m_drawing) {
QPainter painter(&m_image);
painter.setPen(Qt::white);
painter.setBrush(Qt::white);
painter.drawEllipse(event->pos(), m_eraserSize, m_eraserSize);
update();
// 擦除完成后保存绘制结果
saveImage();
m_drawing = false;
}
}
void paintEvent(QPaintEvent* event) override
{
QPainter painter(this);
QRect dirtyRect = event->rect();
painter.drawImage(dirtyRect, m_image, dirtyRect);
}
void resizeEvent(QResizeEvent* event) override
{
if (width() > m_image.width() || height() > m_image.height()) {
int newWidth = qMax(width() + 128, m_image.width());
int newHeight = qMax(height() + 128, m_image.height());
resizeImage(&m_image, QSize(newWidth, newHeight));
update();
}
QWidget::resizeEvent(event);
}
private:
void resizeImage(QImage* image, const QSize& newSize)
{
if (image->size() == newSize)
return;
QImage newImage(newSize, QImage::Format_RGB32);
newImage.fill(qRgb(255, 255, 255));
QPainter painter(&newImage);
painter.drawImage(QPoint(0, 0), *image);
*image = newImage;
}
void saveImage()
{
// 在这里实现保存擦除后的绘图结果
// 可以将图片保存到文件或者进行其他操作
// 示例中暂未给出具体实现方法,可以根据需求自行扩展
}
private:
QImage m_image;
int m_eraserSize;
bool m_drawing;
QPoint m_lastPos;
};
int main(int argc, char** argv)
{
QApplication app(argc, argv);
Whiteboard whiteboard;
whiteboard.resize(800, 600);
whiteboard.show();
return app.exec();
}
这个示例创建了一个继承自QWidget的Whiteboard类,在鼠标事件函数中实现了橡皮擦功能。通过重写mousePressEvent、mouseMoveEvent和mouseReleaseEvent函数,可以实现擦除操作。paintEvent函数用于在窗口上绘制图像。
请注意,在示例中的saveImage函数中,你可以根据需求来保存擦除后的绘图结果,例如将图片保存到文件或进行其他操作。这个示例只是一个简单的演示,具体的实现方式可能会因使用的图形库或绘图框架而有所不同。
内容由零声教学AI助手提供,问题来源于学员提问