【问题标题】:How to detect collision between two QGraphicsPixmapItems if the pixmaps' edges are transparent?如何检测像素图边缘的两个 QGraphicsPixmapItem 之间的碰撞是透明的?
【发布时间】:2018-04-12 18:42:42
【问题描述】:

我有两个QGraphicsPixmapItems,两者的边缘都是透明的,它们不是矩形的。当我尝试使用QGraphicsItem::collidingItems() 时,它只检查它们的边界矩形是否发生碰撞。有没有办法只检测不透明部分的碰撞?

【问题讨论】:

    标签: c++ qt qt5 collision qpixmap


    【解决方案1】:

    您必须将形状模式设置为QGraphicsPixmapItem::HeuristicMaskShape

    QGraphicsPixmapItem::HeuristicMaskShape

    形状是通过调用 QPixmap::createHeuristicMask() 来确定的。这 性能和内存消耗和 MaskShape 差不多


    your_item->setShapeMode(QGraphicsPixmapItem::HeuristicMaskShape);
    

    例子:

    ma​​in.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

    【讨论】:

    • 我已经试过了,但是没有用。 model-&gt;setShapeMode(QGraphicsPixmapItem::HeuristicMaskShape);我将两者都设置为启发式地图。
    • @SkipperHUN 我试过了,效果很好,可能你的图片没有透明胶片,你可以用 zip 格式分享图片。
    • @SkipperHUN 我已经添加了一个示例,下载并执行它,它对我来说可以正常工作。
    • 您的代码也适用于我,但不知何故它在我的项目中不起作用。我决定使用另一种解决方案,它甚至可能比它的工作方式更好。不过感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-20
    相关资源
    最近更新 更多