问题
Trying to copy part of an image as a polygon (specifically a pentagon) but im more interested in how to copy as anything but a rectangle.
The following code only allows to copy as a rectangle.
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:
The general method if you want to get a non-rectangular region is to use setClipPath() of QPainter with 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();
}
来源:https://stackoverflow.com/questions/55714527/qt-qimage-copy-subsection-of-an-image-as-a-polygon