如何检测像素图边缘透明的两个 QGraphicsPixmapItem 之间的碰撞?
How to detect collision between two QGraphicsPixmapItems if the pixmaps' edges are transparent?
我有两个 QGraphicsPixmapItem
,它们的边缘都是透明的,而且它们不是矩形。当我尝试使用 QGraphicsItem::collidingItems()
时,它只检查它们的边界矩形是否发生碰撞。有没有办法只检测非透明部分的碰撞?
您必须将形状模式设置为QGraphicsPixmapItem::HeuristicMaskShape
:
QGraphicsPixmapItem::HeuristicMaskShape
The shape is determine by calling QPixmap::createHeuristicMask(). The
performance and memory consumption is similar to MaskShape
your_item->setShapeMode(QGraphicsPixmapItem::HeuristicMaskShape);
示例:
main.cpp
#include <QApplication>
#include <QGraphicsPixmapItem>
#include <QGraphicsView>
#include <QDebug>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QGraphicsView w;
QGraphicsScene *scene = new QGraphicsScene;
w.setScene(scene);
QList<QGraphicsPixmapItem *> items;
for(const QString & filename: {":/character.png", ":/owl.png"}){
QGraphicsPixmapItem *item = scene->addPixmap(QPixmap(filename));
item->setShapeMode(QGraphicsPixmapItem::HeuristicMaskShape);
item->setFlag(QGraphicsItem::ItemIsMovable, true);
item->setFlag(QGraphicsItem::ItemIsSelectable, true);
items<<item;
}
items[1]->setPos(50, 22);
if(items[0]->collidingItems().isEmpty())
qDebug()<<"there is no intersection";
w.show();
return a.exec();
}
输出:
there is no intersection
完整的例子可以在下面找到link
我有两个 QGraphicsPixmapItem
,它们的边缘都是透明的,而且它们不是矩形。当我尝试使用 QGraphicsItem::collidingItems()
时,它只检查它们的边界矩形是否发生碰撞。有没有办法只检测非透明部分的碰撞?
您必须将形状模式设置为QGraphicsPixmapItem::HeuristicMaskShape
:
QGraphicsPixmapItem::HeuristicMaskShape
The shape is determine by calling QPixmap::createHeuristicMask(). The performance and memory consumption is similar to MaskShape
your_item->setShapeMode(QGraphicsPixmapItem::HeuristicMaskShape);
示例:
main.cpp
#include <QApplication>
#include <QGraphicsPixmapItem>
#include <QGraphicsView>
#include <QDebug>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QGraphicsView w;
QGraphicsScene *scene = new QGraphicsScene;
w.setScene(scene);
QList<QGraphicsPixmapItem *> items;
for(const QString & filename: {":/character.png", ":/owl.png"}){
QGraphicsPixmapItem *item = scene->addPixmap(QPixmap(filename));
item->setShapeMode(QGraphicsPixmapItem::HeuristicMaskShape);
item->setFlag(QGraphicsItem::ItemIsMovable, true);
item->setFlag(QGraphicsItem::ItemIsSelectable, true);
items<<item;
}
items[1]->setPos(50, 22);
if(items[0]->collidingItems().isEmpty())
qDebug()<<"there is no intersection";
w.show();
return a.exec();
}
输出:
there is no intersection
完整的例子可以在下面找到link