【问题标题】:How to compute a QPainterPath from a pixmap如何从像素图计算 QPainterPath
【发布时间】:2014-04-14 01:19:31
【问题描述】:

我有一个 QGraphicsPixmapItem 旋转通过不同的像素图来模拟动画。我需要准确地实现 shape() 函数,以便场景可以正确确定与其他对象的碰撞。每个像素图显然具有略微不同的碰撞路径。有没有一种简单的方法可以从像素图创建 QPainterPath,方法是概述与边界矩形的 alpha 背景接壤的实际图像的彩色像素,而无需编写我自己的复杂算法来尝试手动创建该路径?

我计划以与像素图相同的方式预先绘制这些路径并循环它们。

【问题讨论】:

    标签: qt qt5


    【解决方案1】:

    您可以将QGraphicsPixmapItem::setShapeMode()QGraphicsPixmapItem::MaskShapeQGraphicsPixmapItem::HeuristicMaskShape 一起使用:

    #include <QtGui>
    #include <QtWidgets>
    
    class Item : public QGraphicsPixmapItem
    {
    public:
        Item() {
            setShapeMode(QGraphicsPixmapItem::MaskShape);
            QPixmap pixmap(100, 100);
            pixmap.fill(Qt::transparent);
            QPainter painter(&pixmap);
            painter.setBrush(Qt::gray);
            painter.setPen(Qt::NoPen);
            painter.drawEllipse(0, 0, 100 - painter.pen().width(), 100 - painter.pen().width());
            setPixmap(pixmap);
        }
    
        enum { Type = QGraphicsItem::UserType };
        int type() const {
            return Type;
        }
    };
    
    int main(int argc, char *argv[])
    {
        QApplication app(argc, argv);
    
        QGraphicsView view;
        view.setScene(new QGraphicsScene());
        Item *item = new Item();
        view.scene()->addItem(item);
        // Comment out to see the item.
        QGraphicsPathItem *shapeItem = view.scene()->addPath(item->shape());
        shapeItem->setBrush(Qt::red);
        shapeItem->setPen(Qt::NoPen);
        view.show();
    
        return app.exec();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-07
      • 1970-01-01
      • 2022-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多