如何从像素图计算QPainterPath

时间:2014-04-13 16:31:44

标签: qt qt5

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

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

1 个答案:

答案 0 :(得分:2)

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

#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();
}