2012-08-09 160 views
3

我希望能够使用橡皮筋来选择图像的一个区域,然后删除橡皮筋外部的图像部分并显示新图像。但是,当我现在这样做时,它不会裁剪正确的区域并给我错误的图像。使用QRubberBand在Qt中裁剪图像

#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(); 
} 

任何帮助表示赞赏。

+1

'myRect'将在'MainResizeWindow'坐标中,而不是'copyImage'坐标。检查坐标值。 – cmannett85 2012-08-09 11:12:13

回答

1

这里有两个问题 - 矩形相对于图像的位置以及图像(可能)在标签中缩放的事实。

位置问题:

QRect myRect(myPoint, event->pos()); 

你或许应该将其更改为:

QPoint a = mapToGlobal(myPoint); 
QPoint b = event->globalPos(); 

a = ui->imageLabel->mapFromGlobal(a); 
b = ui->imageLabel->mapFromGlobal(b); 

然后,标签可缩放图像,因为你使用setScaledContents()。所以你需要计算出未缩放图像上的实际坐标。类似这样的东西(未经测试/编译):

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); 
... 
+0

非常感谢!有效! – user1576633 2012-08-09 13:08:10