2011-09-24 124 views
11

我從PNG裝有透明的形狀(藍色):如何在QPainter上使用遮罩?

enter image description here

然後,我對這個形狀上繪製幾個圈(紅色)與QPainter::drawEllipse

enter image description here

的這個結果有點類似於第三畫面與紅色形狀完全覆蓋藍色:

enter image description here

什麼,但是我想是藍色形狀充當紅色面具,結果如下:

enter image description here

QPainter可以做到嗎?

回答

20

這是可能的。假設你加載你的PNG成QImage的,你可以做這樣的事情,從你的圖像創建蒙版:

QImage img("your.png"); 
QPixmap mask = QPixmap::fromImage(img.createAlphaMask()); 

見對方在QImage的create*Mask功能替代品。

然後,它的設置畫家的剪輯區域的一個簡單的問題:

QPainter p(this); 
p.setClipRegion(QRegion(mask)); 

這是一個愚蠢的演示(不要使用代碼-,則圖像加載,面具和地區建立應緩存,他們是潛在的昂貴):

#include <QtGui> 

class W: public QWidget 
{ 
    Q_OBJECT 
    public: 
     W(): QWidget(0) { } 

    protected: 
     void paintEvent(QPaintEvent *) 
     { 
      QPainter p(this); 
      QImage img("../back.png"); 
      QPixmap mask = QPixmap::fromImage(img.createAlphaMask()); 

      // draw the original image on the right 
      p.drawImage(300, 0, img); 

      // draw some ellipses in the middle 
      p.setBrush(Qt::red); 
      for (int i=0; i<100; i+=10) 
       p.drawEllipse(i+150, i, 20, 70); 

      // and do the same thing, but with the mask active 
      p.setClipRegion(QRegion(mask)); 
      for (int i=0; i<100; i+=10) 
       p.drawEllipse(i, i, 20, 70); 
     } 
}; 

將會產生這樣的:對於有用的示例代碼 enter image description here

+0

非常感謝和+1 。 –