本文介绍了QT QImage-将图像的小节复制为多边形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
试图将图像的一部分复制为多边形(特别是五边形),但我对如何将其复制为除矩形以外的其他内容更加感兴趣.
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);
}
}
推荐答案
如果要获取非矩形区域,通常的方法是将QPainter的setClipPath()与QPainterPath一起使用:
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();
}
这篇关于QT QImage-将图像的小节复制为多边形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!