C++ 使用QRubberBand在Qt中裁剪图像
我希望能够使用rubberband选择图像的一个区域,然后删除rubberband之外的图像部分并显示新图像。然而,当我现在这样做的时候,它没有裁剪出正确的区域,并且给了我错误的图像C++ 使用QRubberBand在Qt中裁剪图像,c++,qt,user-interface,crop,C++,Qt,User Interface,Crop,我希望能够使用rubberband选择图像的一个区域,然后删除rubberband之外的图像部分并显示新图像。然而,当我现在这样做的时候,它没有裁剪出正确的区域,并且给了我错误的图像 #include "mainresizewindow.h" #include "ui_mainresizewindow.h" QString fileName; MainResizeWindow::MainResizeWindow(QWidget *parent) : QMainWindow(paren
#include "mainresizewindow.h"
#include "ui_mainresizewindow.h"
QString fileName;
MainResizeWindow::MainResizeWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainResizeWindow)
{
ui->setupUi(this);
ui->imageLabel->setScaledContents(true);
connect(ui->actionOpen, SIGNAL(triggered()), this, SLOT(open()));
}
MainResizeWindow::~MainResizeWindow()
{
delete ui;
}
void MainResizeWindow::open()
{
fileName = QFileDialog::getOpenFileName(this, tr("Open File"), QDir::currentPath());
if (!fileName.isEmpty()) {
QImage image(fileName);
if (image.isNull()) {
QMessageBox::information(this, tr("Image Viewer"),
tr("Cannot load %1.").arg(fileName));
return;
}
ui->imageLabel->setPixmap(QPixmap::fromImage(image));
ui->imageLabel->repaint();
}
}
void MainResizeWindow::mousePressEvent(QMouseEvent *event)
{
if(ui->imageLabel->underMouse()){
myPoint = event->pos();
rubberBand = new QRubberBand(QRubberBand::Rectangle, this);
rubberBand->show();
}
}
void MainResizeWindow::mouseMoveEvent(QMouseEvent *event)
{
rubberBand->setGeometry(QRect(myPoint, event->pos()).normalized());
}
void MainResizeWindow::mouseReleaseEvent(QMouseEvent *event)
{
QRect myRect(myPoint, event->pos());
rubberBand->hide();
QPixmap OriginalPix(*ui->imageLabel->pixmap());
QImage newImage;
newImage = OriginalPix.toImage();
QImage copyImage;
copyImage = copyImage.copy(myRect);
ui->imageLabel->setPixmap(QPixmap::fromImage(copyImage));
ui->imageLabel->repaint();
}
感谢您的帮助。这里有两个问题-矩形相对于图像的位置以及图像(可能)在标签中缩放的事实 立场问题:
QRect myRect(myPoint, event->pos());
您或许应该将此更改为:
QPoint a = mapToGlobal(myPoint);
QPoint b = event->globalPos();
a = ui->imageLabel->mapFromGlobal(a);
b = ui->imageLabel->mapFromGlobal(b);
然后,标签可能会缩放图像,因为您使用了setScaledContents()。所以你需要计算出未缩放图像上的实际坐标。可能是这样(未经测试/编译):
myRect
将位于MainResizeWindow
坐标中,而不是copyImage
坐标中。检查坐标值。
QPixmap OriginalPix(*ui->imageLabel->pixmap());
double sx = ui->imageLabel->rect().width();
double sy = ui->imageLabel->rect().height();
sx = OriginalPix.width() / sx;
sy = OriginalPix.height() / sy;
a.x = int(a.x * sx);
b.x = int(b.x * sx);
a.y = int(a.y * sy);
b.y = int(b.y * sy);
QRect myRect(a, b);
...