QT QImage - 将图像的子部分复制为多边形

问题描述 投票:1回答:1

试图将图像的一部分复制为多边形(特别是五边形),但我更感兴趣的是如何复制除了矩形以外的任何东西。

以下代码仅允许复制为矩形。

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);
    }
}
c++ qt qimage
1个回答
0
投票

如果要获取非矩形区域,一般方法是使用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();
}

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.