QT QImage - Копировать подраздел изображения как многоугольник - PullRequest
1 голос
/ 16 апреля 2019

Попытка скопировать часть изображения в виде многоугольника (в частности, пятиугольника), но меня больше интересует, как копировать как что-либо, кроме прямоугольника.

Следующий код позволяет копировать только как прямоугольник.

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

1 Ответ

0 голосов
/ 16 апреля 2019

Общий метод, если вы хотите получить непрямоугольную область, это использовать setClipPath () из QPainter с 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

...