2014-04-13 18 views
0

我有一個QGraphicsPixmapItem,它可以通過不同的像素圖旋轉來模擬動畫。我需要準確地實現shape()函數,以便場景可以正確地確定與其他對象的碰撞。每個像素映射明顯具有稍微不同的碰撞路徑。有沒有一種簡單的方法來創建一個像素映射的QPainterPath,通過概述邊界矩形的alpha背景邊界的實際圖像的彩色像素,而不必編寫自己的複雜算法來嘗試手動創建該路徑?如何從pixmap中計算QPainterPath

我打算將這些路徑預先繪製,然後像pixmaps一樣循環遍歷它們。

回答

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