2012-08-09 85 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