簡體   English   中英

QT QImage - 將圖像的子部分復制為多邊形

[英]QT QImage - Copy Subsection of an Image as a Polygon

試圖將圖像的一部分復制為多邊形(特別是五邊形),但我對如何復制為矩形以外的任何內容更感興趣。

以下代碼只允許復制為矩形。

QImage copy(const QRect &rect = QRect()) const;
    inline QImage copy(int x, int y, int w, int h) const
        { return copy(QRect(x, y, w, h)); }
void SelectionInstrument::copyImage(ImageArea &imageArea)
{
    if (mIsSelectionExists)
    {
        imageArea.setImage(mImageCopy);
        QClipboard *globalClipboard = QApplication::clipboard();
        QImage copyImage;
        if(mIsImageSelected)
        {
            copyImage = mSelectedImage;
        }
        else
        {
            copyImage = imageArea.getImage()->copy(mTopLeftPoint.x(), mTopLeftPoint.y(), mWidth, mHeight);
        }
        globalClipboard->setImage(copyImage, QClipboard::Clipboard);
    }
}

如果要獲得非矩形區域,一般方法是使用 QPainter 的 setClipPath() 和 QPainterPath:

#include <QtWidgets>

static QImage copyImage(const QImage & input, const QPainterPath & path){
    if(!input.isNull() && !path.isEmpty()){
        QRect r = path.boundingRect().toRect().intersected(input.rect());
        QImage tmp(input.size(), QImage::Format_ARGB32);
        tmp.fill(Qt::transparent);
        QPainter painter(&tmp);
        painter.setClipPath(path);
        painter.drawImage(QPoint{}, input, input.rect());
        painter.end();
        return tmp.copy(r);
    }
    return QImage();
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QImage image(QSize(256, 256), QImage::Format_ARGB32);
    image.fill(QColor("salmon"));
    QPainterPath path;
    QPolygon poly;
    poly << QPoint(128, 28)
         << QPoint(33, 97)
         << QPoint(69, 209)
         << QPoint(187, 209)
         << QPoint(223, 97);
    path.addPolygon(poly);

    QLabel *original_label = new QLabel;
    original_label->setPixmap(QPixmap::fromImage(image));
    QLabel *copy_label = new QLabel;
    copy_label->setPixmap(QPixmap::fromImage(copyImage(image, path)));

    QWidget w;
    QHBoxLayout *lay = new QHBoxLayout(&w);
    lay->addWidget(original_label);
    lay->addWidget(copy_label);
    w.show();

    return a.exec();
}

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM